Julep
Julep

Reputation: 790

Difference between `python file.py` and `python -m file`

In python3:

I have been surprised by how little information I found on these of questions. Maybe I am not searching with the correct terms? Thanks in advance!

Upvotes: 3

Views: 660

Answers (2)

sytech
sytech

Reputation: 41061

What is the difference between calling python path/to/file.py and python -m path.to.file ?

Python -m module_name is a shortcut to invoking a particular module. Often this is an installed package with a __main__.py module inside of it. (e.g. python -m pip invokes pip/__main__.py

So python -m pip is equivalent to python path/to/my/python/lib/site-packages/pip/__main__.py

How does it affect the working directory ? ( os.getcwd() )

It does not

Does it have a link with the presence / absence of an init.py file located in path/to ?

First: There might be some confusion worth clearing up: python -m doesn't take a path as an argument. It takes the name of a module to execute.

So, short answer: no.

Long answer: how a module executed by name with python -m depends on whether or not it is a package. The presence of __init__.py can denote that the directory is the name of a package, like pip is, thusly it will look for __main__ inside of the package.

Upvotes: 3

Aljaž Medič
Aljaž Medič

Reputation: 171

python -m ...

is used for running python library modules, such as pip, IPython etc.

python file.py

however is used to run files with python interpreter.

Upvotes: 2

Related Questions