IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 【python】python -m的简要记录 -> 正文阅读

[Python知识库]【python】python -m的简要记录

前言

在命令行中使用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 #!cmd
-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代码如下:

#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

总结:
相同点:

  1. 当执行python package1python -m package1时,编译器均执行package包下的__main__.py文件;
  2. 执行python package1python -m package1时,编译器均将__main__.py作为主程序入口,所以__name__均==__main__

不同点

  1. python package1sys.path中添加的是__main__.py文件所在的绝对路径;而python -m package1添加的是运行命令行时终端所在的绝对路径;
  2. 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库


  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-03-22 20:32:46  更:2022-03-22 20:33:43 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 20:45:02-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码