文章目录
- Python `-m` 参数的作用
- 直接执行模块代码
- 模块自测试
- 环境隔离
- 避免名称冲突
- 其他:`python3 --help`
Python -m
参数的作用
在Python中,使用-m
参数可以执行一个模块作为脚本。它是用于从命令行直接运行一个Python模块的标志。这种方式具有以下几个方面的作用:
-
直接执行模块代码: 使用
python -m
命令可以直接在命令行中执行一个Python模块,而不需要编写额外的启动脚本。这对于简单的脚本或工具非常方便,因为它们可以作为独立的可执行文件运行。 -
模块自测试: 当一个模块被设计为既可以作为库使用,又可以作为独立脚本运行时,可以将自测试代码放在
__main__
函数中,并使用python -m
来运行该模块以进行测试。这样可以确保模块在被导入时正常运行,同时也能够通过直接执行来验证其功能。
if __name__ == '__main__':
如:
- 环境隔离: 使用
python -m
可以确保在运行指定模块时,使用的是正确版本的Python解释器和所需的依赖项。这对于多个Python环境并存的情况下特别有用,例如在虚拟环境中运行模块。
如:
- 避免名称冲突: 使用
python -m
可以避免与其他具有相同名称的脚本或模块发生名称冲突。通过明确指定模块的完整名称,可以确保执行的是所需的模块。
下面将进一步探讨每个方面的作用。
直接执行模块代码
使用-m
参数,可以直接在命令行中执行Python模块,而不需要创建一个额外的启动脚本。这对于简单的脚本或工具非常方便,因为它们可以作为独立的可执行文件运行。
例如,假设有一个名为my_module.py
的Python模块,其中包含以下代码:
def main():
print("Hello, world!")
if __name__ == "__main__":
main()
要运行该模块,只需使用以下命令:
python -m my_module
这将直接执行my_module.py
中的代码,并输出"Hello, world!"。
模块自测试
当一个模块被设计为既可以作为库使用,又可以作为独立脚本运行时,可以将自测试代码放在__main__
函数中,并使用python -m
来运行该模块以进行测试。
自测试是一种验证模块功能的方法,通常包括一些测试用例和断言语句。通过将自测试代码放在__main__
函数中,可以确保只有在直接执行模块时才会运行这些测试。
继续上面的例子,假设有一个名为my_module.py
的Python模块,其中包含以下代码:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__":
assert add(2, 3) == 5
assert subtract(5, 2) == 3
print("All tests passed!")
在这个例子中,my_module.py
定义了两个函数:add
和subtract
。在__main__
函数中,我们编写了一些简单的测试用例,并使用断言语句进行验证。如果所有的断言都通过,就会输出"All tests passed!"。
要运行这些测试,只需使用以下命令:
python -m my_module
这将执行my_module.py
中的代码,并运行自测试。如果所有的断言通过,将输出"All tests passed!"。
这种方式使得模块可以同时作为可执行脚本和库使用,方便开发者进行测试和验证。
环境隔离
使用python -m
可以确保在运行指定模块时,使用的是正确版本的Python解释器和所需的依赖项。这对于多个Python环境并存的情况下特别有用,例如在虚拟环境中运行模块。
在Python开发中,常常会使用虚拟环境(virtual environment)来隔离不同项目的依赖项。虚拟环境提供了一个独立的Python运行环境,使得每个项目都可以使用其自己的依赖项,而不会相互干扰。
当在虚拟环境中工作时,可以使用python -m
来运行模块,以确保使用的是当前激活的虚拟环境中的Python解释器。
例如,在虚拟环境中安装了名为requests
的第三方库,并编写了一个名为my_module.py
的模块,其中包含以下代码:
import requests
def get_data(url):
response = requests.get(url)
return response.json()
if __name__ == "__main__":
data = get_data("https://api.example.com/data")
print(data)
要在虚拟环境中运行这个模块,只需使用以下命令:
python -m my_module
这将确保在虚拟环境中执行my_module.py
的代码,并且能够正确导入和使用在该环境中安装的requests
库。
避免名称冲突
使用python -m
可以避免与其他具有相同名称的脚本或模块发生名称冲突。通过明确指定模块的完整名称,可以确保执行的是所需的模块。
当系统中存在多个具有相同名称的模块或脚本时,直接使用python <module_name>
可能会导致执行的是不正确的模块。
例如,假设系统中有一个名为my_module.py
的模块,并且还有一个名为my_module.py
的脚本。如果我们只使用python my_module.py
命令来运行,系统可能无法确定要执行哪个文件。
通过使用python -m
,可以明确指定要执行的模块的完整名称。例如:
python -m my_module
这将确保执行的是模块my_module
,而不是同名的脚本。
总之,python -m
提供了一种方便的方式来执行Python模块,并具有环境隔离和名称冲突解决的优势。它是在命令行中直接运行模块的便捷选项,适用于直接执行模块代码、模块自测试、环境隔离和避免名称冲突等场景。
其他:python3 --help
root@nvidia:/ky/tml/ky_ai_factory_test# python3 --help
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X showrefcount: output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on debug builds
-X tracemalloc: start tracing Python memory allocations using the
tracemalloc module. By default, only the most recent frame is stored in a
traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a
traceback limit of NFRAME frames
-X showalloccount: output the total count of allocated objects for each
type when the program finishes. This only works when Python was built with
COUNT_ALLOCS defined
-X importtime: show how long each import takes. It shows module name,
cumulative time (including nested imports) and self time (excluding
nested imports). Note that its output may be broken in multi-threaded
application. Typical usage is python3 -X importtime -c 'import asyncio'
-X dev: enable CPython's "development mode", introducing additional runtime
checks which are too expensive to be enabled by default. Effect of the
developer mode:
* Add default warning filter, as -W default
* Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function
* Enable the faulthandler module to dump the Python traceback on a crash
* Enable asyncio debug mode
* Set the dev_mode attribute of sys.flags to True
* io.IOBase destructor logs close() exceptions
-X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
otherwise activate automatically)
-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
given directory instead of to the code tree
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>).
The default module search path uses <prefix>/lib/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONUTF8: if set to 1, enable the UTF-8 mode.
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
to seed the hashes of str and bytes objects. It can also be set to an
integer in the range [0,4294967295] to get hash values with a
predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
on Python memory allocators. Use PYTHONMALLOC=debug to install debug
hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.
PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.
root@nvidia:/ky/tml/ky_ai_factory_test# python3 --help
usage: python3 [option] … [-c cmd | -m mod | file | -] [arg] …
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don’t write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user’s environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and debug-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-q : don’t print version and copyright messages on interactive startup
-s : don’t add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don’t imply ‘import site’ on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X showrefcount: output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on debug builds
-X tracemalloc: start tracing Python memory allocations using the
tracemalloc module. By default, only the most recent frame is stored in a
traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a
traceback limit of NFRAME frames
-X showalloccount: output the total count of allocated objects for each
type when the program finishes. This only works when Python was built with
COUNT_ALLOCS defined
-X importtime: show how long each import takes. It shows module name,
cumulative time (including nested imports) and self time (excluding
nested imports). Note that its output may be broken in multi-threaded
application. Typical usage is python3 -X importtime -c ‘import asyncio’
-X dev: enable CPython’s “development mode”, introducing additional runtime
checks which are too expensive to be enabled by default. Effect of the
developer mode:
* Add default warning filter, as -W default
* Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function
* Enable the faulthandler module to dump the Python traceback on a crash
* Enable asyncio debug mode
* Set the dev_mode attribute of sys.flags to True
* io.IOBase destructor logs close() exceptions
-X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
otherwise activate automatically)
-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
given directory instead of to the code tree
–check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
file : program read from script file
: program read from stdin (default; interactive mode if a tty)
arg …: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ‘:’-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate directory (or :<exec_prefix>).
The default module search path uses /lib/pythonX.X.
PYTHONCASEOK : ignore case in ‘import’ statements (Windows).
PYTHONUTF8: if set to 1, enable the UTF-8 mode.
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to ‘random’, a random value is used
to seed the hashes of str and bytes objects. It can also be set to an
integer in the range [0,4294967295] to get hash values with a
predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
on Python memory allocators. Use PYTHONMALLOC=debug to install debug
hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.
PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.