前言
在命令行中使用python 的标准格式为: python [option] ... [-c cmd | -m mod | file | -] [arg] ... 运行python --help 可以查看具体可用的选项参数与环境变量释义
python --help
usage: python [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 : turn on parser debugging output (for experts only, only works on
debug builds); 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
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X oldparser: enable the traditional LL(1) parser; also PYTHONOLDPARSER
-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 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.
PYTHONPLATLIBDIR : override sys.platlibdir.
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.
本文更进一步地介绍一下python -m 应用 如上图的 python --help 所示,python -m 主要是将python 的模块代码作为脚本运行,单看这句话,可能会有所疑惑“那python -m script 与之间的python script.py 有啥差别呢?”。
1. python -m script 与 python script.py的异同点
考虑如下文件结构:
1.1 运行package时
package1.__main__.py 代码如下:
print("I am package1.__main__.py")
import sys
print(sys.path)
print(__name__)
print(__package__)
在python_m路径下终端运行python package1 显示如下:
I am package1.__main__.py
['/media/hove/Backup/python_m/package1', '/media/hove/Backup/ros_workspace/devel/lib/python2.7/dist-packages', '/opt/ros/melodic/lib/python2.7/dist-packages', '/home/hove/anaconda3/lib/python39.zip', '/home/hove/anaconda3/lib/python3.9', '/home/hove/anaconda3/lib/python3.9/lib-dynload', '/home/hove/anaconda3/lib/python3.9/site-packages', '/home/hove/anaconda3/lib/python3.9/site-packages/locket-0.2.1-py3.9.egg']
__main__
在python_m路径下终端运行python -m package1 显示如下:
I am package1.__main__.py
['/media/hove/Backup/python_m', '/media/hove/Backup/ros_workspace/devel/lib/python2.7/dist-packages', '/opt/ros/melodic/lib/python2.7/dist-packages', '/home/hove/anaconda3/lib/python39.zip', '/home/hove/anaconda3/lib/python3.9', '/home/hove/anaconda3/lib/python3.9/lib-dynload', '/home/hove/anaconda3/lib/python3.9/site-packages', '/home/hove/anaconda3/lib/python3.9/site-packages/locket-0.2.1-py3.9.egg']
__main__
package1
总结: 相同点:
- 当执行
python package1 与python -m package1 时,编译器均执行package包下的__main__.py 文件; - 执行
python package1 与python -m package1 时,编译器均将__main__.py 作为主程序入口,所以__name__ 均==__main__ 。
不同点
python package1 在sys.path 中添加的是__main__.py 文件所在的绝对路径;而python -m package1 添加的是运行命令行时终端所在的绝对路径;python package1 并无保留文件结构,__package__==None ;而python -m package1 保留文件结构__package__==package1 ;
1.2 当package1中有相对导入文件时
package1.relative_import.py 代码如下:
import sys
print(sys.path)
print(__package__)
from . import function
在python_m路径下终端运行python package1/relative_import.py 显示如下:
['/media/hove/Backup/python_m/package1', '/media/hove/Backup/ros_workspace/devel/lib/python2.7/dist-packages', '/opt/ros/melodic/lib/python2.7/dist-packages', '/home/hove/anaconda3/lib/python39.zip', '/home/hove/anaconda3/lib/python3.9', '/home/hove/anaconda3/lib/python3.9/lib-dynload', '/home/hove/anaconda3/lib/python3.9/site-packages', '/home/hove/anaconda3/lib/python3.9/site-packages/locket-0.2.1-py3.9.egg']
Traceback (most recent call last):
File "/media/hove/Backup/python_m/package1/relative_import.py", line 3, in <module>
from . import function
ImportError: attempted relative import with no known parent package
在python_m路径下终端运行python -m package1.relative_import 显示如下:
['/media/hove/Backup/python_m', '/media/hove/Backup/ros_workspace/devel/lib/python2.7/dist-packages', '/opt/ros/melodic/lib/python2.7/dist-packages', '/home/hove/anaconda3/lib/python39.zip', '/home/hove/anaconda3/lib/python3.9', '/home/hove/anaconda3/lib/python3.9/lib-dynload', '/home/hove/anaconda3/lib/python3.9/site-packages', '/home/hove/anaconda3/lib/python3.9/site-packages/locket-0.2.1-py3.9.egg']
package1
I am package1.function
总结:
- 由于
python package1/relative_import.py 中的sys.path 定位到/media/hove/Backup/python_m/package1 ,且无保留文件结构,编译器无法识别该文件的父文件夹,因此直接运行会出现错误; python -m package1.relative_import 保留文件结构,故可以使用相对路径。
可将代码修改如下:
import sys
print(sys.path)
print(__package__)
if __package__ !=None:
from . import function
else:
sys.path.append('/media/hove/Backup/python_m')
import function
1.3 python -m 的其他优势
当运行已安装python库或者系统内嵌python库时,python -m 可无需了解库的具体安装地址即可运行,具体见第二部分的应用案例。
2. python -m 应用案例
案例一:
python -m http.server 8888
解释: 运行http.server模块搭建本地局域网,指定端口号为8888,此时运行该命令的文件路径即为其他设备的访问路径。具体见用python -m http.server搭一个简易的本地局域网。
案例二:
python3 -m pydoc -p 9999
解释: 运行pydoc 模块,在9999端口上启动http服务,生成HTML格式的官方帮助文档,并可通过浏览器访问。
案例三:
python -m pdb xxx.py
解释 运行pdb调试模块,在调试模式下运行" xxx.py "脚本
案例四:
“python3.6 -m pip install numpy”
解释: 指定python3.6的pip模块安装numpy库
|