What is the purpose of the -m switch?

Could you explain to me what the difference is between the call

python -m mymod1 mymod2.py args 

and

 python mymod1.py mymod2.py args 

It seems that in both cases mymod1.py is mymod1.py and sys.argv is

 ['mymod1.py', 'mymod2.py', 'args'] 

So what is -m for?

+97
source share
2 answers

The first line of the Rationale PEP 338 section says:

Python 2.4 adds the -m command line switch to allow the placement of modules using the Python module namespace for execution as scripts. Motivational examples were standard library modules such as pdb and profile, and the Python 2.4 implementation is suitable for this limited purpose.

That way, you can specify any module in the Python search path this way, and not just the files in the current directory. You are correct that python mymod1.py mymod2.py args has exactly the same effect. The first line of the Scope of this proposal section says:

In Python 2.4, a module located using -m runs just as if its filename were provided on the command line.

With -m perhaps more, for example, working with modules that are part of a package, etc. As for the rest of PEP 338. Read it for more information.

+94
source

Another thing that I think is worth noting when to perform

 python -m some_module some_arguments 

The python interpreter will look for the " main .py" file in the module path to execute. This is equivalent to:

 python path_to_module/__main__.py somearguments 

It will execute the contents after:

 if __name__ == "__main__": 

If the file does not exist, this module cannot be executed directly.

0
source

Source: https://habr.com/ru/post/1263014/


All Articles