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

I am new to Python (and for programming), and although it is well-documented, I can’t understand what the -m directive means exactly (specifically in creating a virtual environment: python3 -m venv my_env .

As far as I can read from the documentation, this means "run the library module as a script": in fact, this concept cannot be understood and what is the difference in executing a command without -m .

Also, is this a property of Python 3?

+4
source share
2 answers

Python modules are just script files that are in a place where Python can find them. As with all scenarios, you can simply run them directly if you know where they are, for example. python /path/to/module.py .

Well-designed modules usually do nothing but adjust the material (for example, functions and types that you can import), but usually they usually do not have a visible side effect. That is why you can do import sys and nothing happens.

However, some modules may offer useful things when they are run from the command line. Examples for this include venv , but also http.server or idlelib : these are all ordinary modules that can be imported from other modules without any side effects.

But when they are executed directly, they all do things (for example, venv sets up a virtual environment, http.server starts a simple HTTP server, and idlelib starts 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 to recognize the script / module directly, or it is simply imported from some other module. You can learn more about the question What does if __name__ == '__main__': do? .

So, you can run the module directly using python /path/to/module.py , as we installed earlier. But this requires that you know the full path to the module. Where the -m option is turned on: for modules that can usually be imported only with import modulename , you can use python -m modulename to run this module directly. As if you entered the full path to it.

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

+14
source

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

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

Now, if you use any class or function or any first_script.py object in hellomodule.py, you need to run hellomodule.py as a module, so the command will be changed to

python -m HelloModule/hellomodule

and you must run this command from outside the HelloModule directory.

+1
source

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


All Articles