[英]Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt?
This works in the Python 3.3.2 Shell 这适用于Python 3.3.2 Shell
>>> import datetime
>>> print(datetime.datetime.utcnow())
2013-07-09 19:40:32.532341
That's great! 那很棒! I then wrote a simple text file named "datetime.py"
然后我写了一个名为“datetime.py”的简单文本文件
#Date time
import datetime
print(datetime.datetime.utcnow())
#Prints GMT, which is named Universal Coordinated Time
# Which is UTC because in French it's something like
# Universahl Tyme Coordinatay
#Outputs something like 2013-07-09 15:15:19.695531
C:\Python33\myscripts>ls
__pycache__ ex1.out ex2.out ex3.py helloworld.py read1.py
datetime.py ex1.py ex2.py first.py pythonintoimportexport.py test.py
Here is where it gets mysterious! 这是神秘的地方!
C:\Python33\myscripts>python datetime.py
Traceback (most recent call last):
File "datetime.py", line 2, in <module>
import datetime
File "C:\Python33\myscripts\datetime.py", line 3, in <module>
print(datetime.datetime.utcnow())
AttributeError: 'module' object has no attribute 'utcnow'
Why does the same code work in the Python Shell, but not when run as a script? 为什么相同的代码在Python Shell中有效,但在作为脚本运行时却不行?
The problem is that file is recursively importing itself, instead of importing the built-in module datetime
: 问题是文件以递归方式导入自身,而不是导入内置模块的
datetime
:
Demo: 演示:
$ cat datetime.py
import datetime
print datetime.__file__
$ python datetime.py
/home/monty/py/datetime.pyc
/home/monty/py/datetime.pyc
This happens because the module is searched in this order: 发生这种情况是因为按以下顺序搜索模块 :
Simply change the name of datetime.py
to something else. 只需将
datetime.py
的名称更改为其他名称即可。
As @Sukrit Kalra says, don't use datetime.py
as your file name. 正如@Sukrit Kalra所说,不要使用
datetime.py
作为文件名。 Python is getting confused with which datetime
is which (and is importing itself!). Python正在与哪个
datetime
混淆(并且正在导入自己!)。 Maybe; 也许;
$ mv datetime.py my_datetime.py
Never use filenames same as module names. 切勿使用与模块名称相同的文件名。 Change filename to something else apart from
datetime.py
. 除了
datetime.py
之外,将文件名更改为其他内容。
Naming your file datetime
causes Python to import the file you're running as a module. 命名文件
datetime
会导致Python导入您作为模块运行的文件。 For example, look at sys.path
. 例如,查看
sys.path
。 Mine, for example, is ['', '/usr/lib/python3.3', ...]
, which means that Python looks FIRST in the current working directory (the ''
) for modules. 例如,我的是
['', '/usr/lib/python3.3', ...]
,这意味着Python在模块的当前工作目录( ''
)中看起来是FIRST。 And because anything that ends in .py can be imported as a module, it imports the script that you're actually running (which, if I'm not mistaken, actually causes it to be run twice, once as __main__
and once as a module). 并且因为以.py结尾的任何内容都可以作为模块导入,它会导入您实际运行的脚本(如果我没有弄错,实际上会导致它运行两次,一次作为
__main__
,一次作为一个模块)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.