0

I am trying to run a python script from CMD (let's say sample.py) and I have added the directory of sample.py to my PATH. When I run "sample.py" in CMD it opens the file in my editor meaning it recognizes it. However, when I run "python sample.py" (python.exe added to path) I get the error:

python: can't open file 'sample.py': [Errno 2] No such file or directory".

Why does sample.py not run with python but opens otherwise? I am using a Windows machine.

Naman Jain
  • 1
  • 1
  • 3
  • Try going to that directory and run the file. Because I am not sure where and what path you have added. – Hayat Dec 05 '18 at 12:45
  • You need to add a Windows tag. In Linux/MacOS/etc, this is usually handled by adding a shebang to the top of the file, making the file executable, and setting `PATH` correctly. For Windows, see [the docs](https://docs.python.org/2/faq/windows.html#how-do-i-make-python-scripts-executable). – user1071847 Dec 05 '18 at 12:53
  • 1
    Adding to path means the OS can run Python without the full file path. It also means that the OS can open your .py without the full file path. But when you run "python [filename]" you're no longer asking the OS to open your file, you're asking Python to open it. Python needs to know where the file is. See Guidot's answer. – KuboMD Dec 05 '18 at 12:55
  • Try "python -m sample" – shrewmouse Dec 05 '18 at 13:31

2 Answers2

1

Adding the directory of the Python file to run to PATH does not help, since it is only used by the operating system to resolve directly executable stuff.

In this case you need to specify the path as in

python path/to/script/script.py

An alternative is to add a special first line into the Python file as in this question and make it directly executable (depending on OS used).

For details you may also want to refer to the corresponding PEP-397.

guidot
  • 5,095
  • 2
  • 25
  • 37
  • Thanks! That makes sense. What would be a way to successfully execute "python sample.py" (without including the full path) in the windows terminal? – Naman Jain Dec 05 '18 at 18:13
0

You have to add the full path to your python.exe file to the PATH environment variable, not your sample.py file.

Then your command

python sample.py

will launch your script file, supposing you enter that command from the directory containing the sample.py file.

MarianD
  • 13,096
  • 12
  • 42
  • 54