Eric - 7 months ago 70
Python Question

# 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


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