Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between running ./file.py and python file.py?

When I run Python script from the command line

./file.py

it is interpreted differently(fails with a bunch of errors) from when I run it using:

python file.py

Why are they executed differently?

like image 441
ejboy Avatar asked Aug 12 '14 04:08

ejboy


People also ask

What is run py in Python?

Source code: Lib/runpy.py. The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the -m command line switch that allows scripts to be located using the Python module namespace rather than the filesystem.

What is difference between py and Python?

py is the Python launcher which is a utility that comes with Python installations on Windows. It gets installed into C:\Windows\ so it's available without requiring PATH modifications.

What is the difference between .py file and .PYC file?

. py files contain the source code of a program. Whereas, . pyc file contains the bytecode of your program.


1 Answers

On Unix-like systems:

  • ./file.py requires file.py to be executable (e.g., chmod a+x file.py).
  • ./file.py runs the script with whichever interpreter is specified in its shebang line; python file.py runs it with whichever interpreter named python is highest on your $PATH. If you have multiple versions of Python, this can make a big difference.

If you don't know which python is highest on your $PATH, type which python and it will tell you.

If you want the shebang line to run the python that's highest on your $PATH, write it as:

#!/usr/bin/env python

On Windows:

  • ./file.py runs the script with whatever application is registered to handle *.py files, whereas python file.py runs it with whichever interpreter named python.exe is highest on your %PATH%. Again, if you have multiple versions of Python, this can make a big difference.

Note that Windows cmd.exe, unlike Unix shells, doesn't care about shebangs, only extensions. However, if you've installed a new enough version of Python, the application registered to handle *.py files will be the PEP 397 Python launcher, which does look at shebangs. (You can also get the launcher separately for older versions of Python.)


From your comments, the first line is:

just a start of the program, i.e. import socket

It sounds like you don't have a shebang line at all. That means that, if you're on a Unix-like system, ./file.py will run it with the default interpreter—which is /bin/sh on Unix and most Unix-likes, which isn't a Python interpreter at all. So you will probably get a bunch of confusing errors, probably starting with something like import: command not found.

like image 150
abarnert Avatar answered Nov 14 '22 23:11

abarnert