Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt?

后端 未结 4 1350
执念已碎
执念已碎 2020-12-06 13:48

This works in the Python 3.3.2 Shell

Inside the Python 3.3.2 Shell

>>> import datetime
>>> print(datetime.datetime.utcnow())
2013         


        
相关标签:
4条回答
  • 2020-12-06 14:27

    As @Sukrit Kalra says, don't use datetime.py as your file name. Python is getting confused with which datetime is which (and is importing itself!). Maybe;

     $ mv datetime.py my_datetime.py
    
    0 讨论(0)
  • 2020-12-06 14:33

    Naming your file datetime causes Python to import the file you're running as a module. For example, look at sys.path. Mine, for example, is ['', '/usr/lib/python3.3', ...], which means that Python looks FIRST in the current working directory (the '') for modules. 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).

    0 讨论(0)
  • 2020-12-06 14:37

    Never use filenames same as module names. Change filename to something else apart from datetime.py .

    0 讨论(0)
  • 2020-12-06 14:44

    The problem is that file is recursively importing itself, instead of importing the built-in module 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:

    • the directory containing the input script (or the current directory).
    • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    • the installation-dependent default.

    Simply change the name of datetime.py to something else.

    0 讨论(0)
提交回复
热议问题