What does it mean to "run library module as a script" with the "-m" option?

Question:

I’m new to Python (and to programming as well) and, although well documented, I cannot understand what exactly means the -m directive (precisely in the creation of a virtual environment: python3 -m venv my_env.

As far as I can read from the documentation, it stands for “run library module as a script”: it is in fact this concept that I cannot figure out and what is the difference in running the command without the -m.

Moreover, it this a characteristic of Python 3?

Asked By: Pankus

||

Answers:

This is not a property of python3. You need to use -m in the case of modular script. Say for example you have folder structure like this

|-HelloModule
  |_ __init__.py
  |_ hellomodule.py
|_ first_script.py

Now if you are using any class or function or any object of first_script.py into hellomodule.py then you have to run the hellomodule.py as a module means the command will be changed to

python -m HelloModule/hellomodule

and you have to run this command from the outside of the HelloModule directory.

Answered By: P.Madhukar

Python modules are just script files that are located in a place where Python can find them. As with all scripts, you can just run them directly if you know where they are, e.g. python /path/to/module.py.

Properly designed modules usually do nothing except set up stuff (e.g. functions and types you could import), but they usually won’t have any visible side effect. That’s why you can do import sys and nothing happens.

However, some modules may offer useful stuff when they are run from the command line. Examples for that include venv but also http.server or idlelib: All of those are regular modules that can be imported from other modules without side effects.

But when executed directly, they all do things (e.g. venv sets up a virtual environment, http.server runs a simple HTTP server, and idlelib runs IDLE). This is usually done with the following check:

if __name__ == '__main__':
    print('Module is being executed directly, so do stuff here')

This is a special way of recognizing of a script/module is being executed directly, or whether it’s just being imported from some other module. You can learn more about the question “What does if __name__ == '__main__': do?”.

So, you can run a module directly using python /path/to/module.py as we established before. But this requires you to know the full path to the module. That’s where the -m option comes into play: For modules that can usually be imported just using import modulename, you can use python -m modulename to run that module directly. Just as if you typed the full path to it.

So for our above examples, we can just use python -m venv, python -m http.server. or python -m idlelib.

Answered By: poke
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.