Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I have to add 'python' before invoking Python script?

Tags:

python

I am new to programming, and Python is my first language. I've added Python to my Path, but when I use the Command Prompt, I don't have to add python before myscript.py as opposed to many tutorials I've seen. Here is an example:

C:\User\MyName>Welcome.py
Welcome to Python
Python is fun

When I enter 'python', there is a subsequent error:

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

Do I really need the 'python'? Thanks in advance!

like image 962
user78338 Avatar asked Jul 19 '13 23:07

user78338


2 Answers

If you followed the Python on Windows FAQ, it seems that the standard Python installer has already taken the liberty of associating .py files with an open command to ..\..\Python\python.exe "%1" %*.

How do I make Python scripts executable?

On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.

Who'd have thunk! This isn't the way it used to be four years ago when I first installed Python on my Windows machine.

like image 107
2rs2ts Avatar answered Oct 14 '22 08:10

2rs2ts


Yes and no.
It really depends on how the script is written.

On most unix systems (Linux, Mac OS), you could include #!/bin/python to the top of (as the first line of) your script and therefore execute it by just calling the filename on the command line. That first line tells the shell that this file contains a python program. The shell then uses the python interpreter to execute the file (translation: it translates your $ Welcome.py to $ /bin/python Welcome.py <- note that python is being called explicitly and that it's the same path as what's on the first line of your file).

Presumably, the Windows OS can also be instructed in the same way, though I have never been able to do it myself, nor have I tried very hard (I moved away from windows about 5 years ago). This is why you'll need to explicitly call python.
Calling python tells the OS: "hey! open that program called python and tell it to run the file Welcome.py". This is exactly what the command /bin/python Welcome.py does on a unix system

like image 23
inspectorG4dget Avatar answered Oct 14 '22 07:10

inspectorG4dget