简体   繁体   中英

NameError when running .py file from CMD Windows 10

I am trying to run a .py file created in a text editor from the CMD line in Windows 10. Here is my very simple code:

def main():
    print 'It works!'

if __name__ == '__main__':
    main()

When I run from CMD line, which is already in python 2.7 mode, i type

pytest.py

which is the name of the file. However, now the CMD line says:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pytest' is not defined

CMD截图

CMD截屏2

You cannot run the .py file from the Python interpreter (starting with >>> )

So, you need to see C:\\Users\\Eric> python pytest.py to run python on your file.

Or , you can run only python , then you must import the file.

>>> import pytest
>>> pytest.main()

Both cases assume the CMD is at the same directory as your file. If not, you must cd to that proper directory first, or use

C:\Users\Eric> python C:\Users\Eric\full\path\to\pytest.py

When you start a terminal in windows via CMD, you are in the Windows Command Line. Here you can run your python code by entering

python yourpythoncode.py

Or you can choose to start the python interpreter by entering just :

python

In the interpreter you can run your python program by importing it

import yourpythoncode

If yourpythoncode has a line like

if ___name___ = ___main___:
    main()

then it is protected from autorunning the code. So to run your code your still need to call it explicit by entering :

main()

Either make the file executable or supply it to python program to run it

python pytest.py

If you are running the file from within the python interpreter, then you need to exit that using Ctrl + Z and run it from the command line the way I mentioned above.

Note: You will need to change to the directory where pytest.py is located in for the above command to work; or you need to supply the path to the file. For example, from your pictures, you are in the root directory ie C:\\Users\\Eric ; if you open file explorer on windows and navigate to where your file is located, you can right click the file and view properties and this should show you the location. Then in your command prompt, you need to type cd C:\\location\\you\\just\\copied\\ then after that you should be able to run the file using the python command above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM