【问题标题】:Python 2.7 on Mac OSX. can not import random package Environment getting corruptedMac OSX 上的 Python 2.7。无法导入随机包环境损坏
【发布时间】:2013-11-06 03:32:33
【问题描述】:
Last login: Tue Nov  5 15:13:08 on ttys000 
Preetis-MacBook-Pro:~ preetigupta25$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
Preetis-MacBook-Pro:~ preetigupta25$ /Library/Frameworks/Python.framework/Versions/2.7/bin/python
Python 2.7.6rc1 (v2.7.6rc1:4913d0e9be30+, Oct 27 2013, 20:52:11) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> ^D
Preetis-MacBook-Pro:~ preetigupta25$ /usr/bin/python
Python 2.7.6rc1 (v2.7.6rc1:4913d0e9be30+, Oct 27 2013, 20:52:11) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> ^D
Preetis-MacBook-Pro:~ preetigupta25$ cd /Users/preetigupta25/Documents/lab\ work/Economic\ modelling/src
-bash: cd: /Users/preetigupta25/Documents/lab work/Economic modelling/src: No such file or directory
Preetis-MacBook-Pro:~ preetigupta25$ cd /Users/preetigupta25/Documents/lab\ work/Economic\ modelling/Preeti_model/src
Preetis-MacBook-Pro:src preetigupta25$ ./model.py
Traceback (most recent call last):
  File "./model.py", line 5, in <module>
    from random import generate_random_no
  File "/Users/preetigupta25/Documents/lab work/Economic modelling/Preeti_model/src/random.py", line 4, in <module>
    from random import random
ImportError: cannot import name random
Preetis-MacBook-Pro:src preetigupta25$ python
Python 2.7.6rc1 (v2.7.6rc1:4913d0e9be30+, Oct 27 2013, 20:52:11) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "random.py", line 4, in <module>
    from random import random
ImportError: cannot import name random
>>> 

我的 Mac OSX 上有 Python 2.7.6。我正在尝试在我的 python 脚本中包含随机模块,但它不起作用。

如果您在上面看到,import random 在 python 提示符下可以正常工作。但是一旦我运行我的脚本:(它就找不到随机模块,之后我也无法在 python 提示符下导入随机。
我的脚本将 #!/usr/bin/python 作为第一行。

import os
import sys

from random import random

class generate_random_no:
    def __init__(self):
        #rand = random()
        pass
    def get_random_number(self):
        return randint()

    def get_random_number(self, upperbound):
        return randrange(upperbound)

【问题讨论】:

  • 看起来问题出在from random input ... 你确定模块random 包含generate_random_no 吗?我建议安装 ipython,这样您就可以使用 TAB 浏览任何模块的子模块 - 这很有帮助。
  • 在命令行中尝试:from random input random 可以吗?

标签: python macos python-2.7 random


【解决方案1】:

避免使用 random.py 这样的文件名。它将隐藏标准库模块random

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 2016-07-07
    • 2012-06-29
    • 2018-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多