0

I wrote program in one text file "program.py".I saved this file on desktop. I want to execute this through command line

Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\x0266161>cd C:\Users\x0266161\Desktop\

C:\Users\x0266161\Desktop>python program.py
hello world

Now is it possible for me to execute the program without changing to the directory where program is stored.

when I try I am getting below error

C:\Users\x0266161\Desktop>cd ..

C:\Users\x0266161>cd ..

C:\Users>cd ..

C:\>python program.py
python: can't open file 'program.py': [Errno 2] No such file or directory

C:\>

I have set environmental variable to this path C:\Users\x0266161\Desktop.

McGrady
  • 10,869
  • 13
  • 47
  • 69

2 Answers2

0

When you're typing

C:> python program.py

you are passing the file "program.py" as an argument to the interpreter. As a matter of fact, this file can only be accessed if it is in the current directory.

Now, I'm not a regular windows user, but your program.py must be executable and should have a shebang (on Linux or windows + cygwin) to be runnable from path.

This particular post can help you : https://stackoverflow.com/a/7574585/8462076

Otherwise you can use something like py2exe to create an executable file (i.e. ms Portable Executable .exe file)

Also, if you have file association with .py file and your python interpreter, you can simply double-click to run it.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
peyo
  • 442
  • 3
  • 9
0

Just run program.py without python in front of it. Windows will search PATH for the program instead of for Python, and since Python registers .py as files it processes, Python will be run with the file anyway.

If you add .py to the PATHEXT environment variable, you can just type program as well.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251