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

This works in Python 3.3.2 Shell

Inside Python 3.3.2 Shell

>>> import datetime >>> print(datetime.datetime.utcnow()) 2013-07-09 19:40:32.532341 

It's great! Then I wrote a simple text file called "datetime.py"

Inside 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 something like # Universahl Tyme Coordinatay #Outputs something like 2013-07-09 15:15:19.695531 

File Proof

 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 

That's 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' 

Question

Why does the same code work in the Python shell, but not when run as a script?

+6
source share
4 answers

The problem is that the file recursively imports itself, rather than importing the built-in datetime module:

Demo:

 $ cat datetime.py import datetime print datetime.__file__ $ python datetime.py /home/monty/py/datetime.pyc /home/monty/py/datetime.pyc 

This is because the module

+11
source

As @Sukrit Kalra says, do not use datetime.py as the name of your file. Python gets confused what datetime is (and imports itself!). May be,

  $ mv datetime.py my_datetime.py 
+2
source

Never use file names like module names. Change the file name to something other than datetime.py .

+1
source

Naming your datetime file causes Python to import the file you are using as a module. For example, see sys.path . For example, Mine has the value ['', '/usr/lib/python3.3', ...] , which means that Python looks FIRST in the current working directory ( '' ) for the modules. And since everything that ends with .py can be imported as a module, it imports the script that you are actually running (which, if I'm not mistaken, actually makes it run twice, once as __main__ and once as a module )

0
source

Source: https://habr.com/ru/post/949045/


All Articles