当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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

网友答案:

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 i.e. 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

网友答案:

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()
分享给朋友:
您可能感兴趣的文章:
随机阅读: