Importing and using modules in python
New to开发者_Python百科 python and trying to do a random number generator. However, I am having trouble importing the random module. I get a AttributeError when I try to use anything from the random module. Thanks for your help.
#!/usr/bin/python -tt
import random
def main():
x = random.randint(1,1000)
print x
if __name__ == '__main__':
main()
You probably have a file named random.py (or pyc) in your current directory. You can find out where the random module you're using comes from by doing this:
import random
print(random.__file__)
The python importing system vaguely works as follows.
- A line like
import foo
is executed. - Python looks through the directories in
sys.path
which is a list in the order in which they occur. The first entry insys.path
is the directory in which the main file lives. - When Python finds a file named "foo.py", it executes it and places the global namespace of that file in the module
sys.modules['foo']
. - Python binds that module to the name
foo
in the scope in which the original import occurs.
So when you name the file random.py
, python finds that file before it searches through the files in the standard library. You are "shadowing" the random
module with your file.
This is simplified and doesn't give the full picture. For example, it ignores .pyc files.
Okay, dont name your python program as random.py
name it as something else. The interpreter is getting confused by its module and the your program.
I solved the same problem reading this post. I had my file named random.py Wouldn't it be better to start filename with capital letters so it doesn't match with python module, cos I rookie like me wouldn't be familiar with many python modules. Thanks
精彩评论