← All writing

Python -m parameter explanation

When "python -m " is entered on the command line, this means to run the program using Python's built-in modules, where is the name of the module to be run. This is similar to using "import " and running "module-name.run()" in a Python script.

阅读中文版 →

1. Python -m parameter explanation

What does the parameter of python -m mean when called by shell?

When typing "python -m " , this means running the program using Python's built-in modules, whereis the name of the module to run. This is similar to using "import " and run "module-name.run()".

For example: "python -m http.server" will start Python's built-in HTTP server, which can access files in the current directory in the browser. "python -m unittest discover" will find and run all unit test scripts named test_*.py in the current directory.

module-name.run() Do I need to write the run function in the module myself?

No need. When calling "python -m " , Python will automatically look for and run a function named "run()" in the module. If the function does not exist, a function named "main()" in the module is looked for and run.

In most cases, if the module is an executable program, you should write a function called "main()" inside it and write the program logic in that function.

If the module is a library rather than an executable program, there is no need to write a "main()" or "run()" function. These functions will not be called because when the module is imported, its functions and variables can be called from other code.