文章目录

  • Python命令行参数概览
    • -c cmd参数示例
    • -m mod参数示例
    • file参数示例
    • - 参数示例
  • 命令行选项详解
    • -b 选项
    • -B选项
    • -d选项
    • -E选项
    • -h / -? / --help选项
    • -i选项
    • -I选项
    • -O与-OO选项
    • -q选项
    • -s选项
    • -S选项
    • -u选项
    • -v选项
    • -V / --version选项
    • -W arg选项
    • -x选项
    • -X opt选项
    • --check-hash-based-pycs always|default|never选项
  • 参考

Python命令行参数概览

使用–help选项可以列出Python 3.7.3支持的所有命令行参数。

C:\Users\tsu5>py -3 --help
usage: C:\Python\Python3.7.3\python.exe [option] ... [-c cmd | -m mod | file | -] [arg] ...

python.exe后面可以跟着

  • [option] …:多个可选选项,后续章节详细讲解每个选项。
  • [-c cmd | -m mod | file | - ] [arg] …:各种方式指定要执行的Python程序以及可能的参数
    • [-c cmd]:执行Python语句后退出
    • [-m mod]:把库模块当作脚本运行(同时也终止了选项列表,即其他选项必须放在-m之前)
    • [file]:执行Python脚本
    • [-]:Python执行后,出现交互提示界面,从标准输入读取Python语句,并执行。
    • [arg] …:指定的一个或多个arg,会作为参数传递给Python脚本/库模块

-c cmd参数示例

我经常用这种方式把Python当成个简单的计算器。

C:\Users\tsu5>py -3  -c "print(1080/24)"
45.0

-m mod参数示例

C:\Users\tsu5>py.exe -3 -m pydoc
pydoc - the Python documentation tool
...C:\Users\tsu5>py.exe -3 -m unittest
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK

还可以使用 python -m venv创建虚拟环境,详情参看
虚拟环境:pyvenv过时;使用python -m venv命令

file参数示例

(py3.7_env) tony@ubtu-nas918:~$ cat hello3.py
#!/usr/bin/python3print("Hello, Python!")(py3.7_env) tony@ubtu-nas918:~$ python hello3.py
Hello, Python!

- 参数示例

(py3.7_env) tony@ubtu-nas918:~$ python - <<EOF
> print("Hello, Standard in!")
> EOF
Hello, Standard in!

或者省略 - 参数

(py3.7_env) tony@ubtu-nas918:~$ python <<EOF
print("Hello, Standard in!")
EOFHello, Standard in!

命令行选项详解

-b 选项

-b     : issue warnings about str(bytes_instance), str(bytearray_instance)and comparing bytes/bytearray with str. (-bb: issue errors)

对str(bytes_instance),str(bytearray_instance) 以及将bytes/bytearray与str比较时,产生警告信息。如果使用了 -bb 选项,则产生错误信息。

下面是同一个Python脚本,未指定-b选项,指定-b选项,指定-bb选项,的运行效果。

# mybytes.py文件:定义了bytes示例,然后将其转换成字符串输出。
(py3.7_env) tony@ubtu-nas918:~$ cat mybytes.pymy_bytes=b'0\x300\x31'
print("my_bytes type is: " + str(type(my_bytes)))
print(str(my_bytes))# 不指定-b选项,python正常打印转换后的字符串
(py3.7_env) tony@ubtu-nas918:~$ python mybytes.py
my_bytes type is: <class 'bytes'>
b'0001'# 指定-b选项,python打印转换的字符串之前,产生警告信息,但是继续执行
(py3.7_env) tony@ubtu-nas918:~$ python -b mybytes.py
my_bytes type is: <class 'bytes'>
---> 警告信息行:mybytes.py:4: BytesWarning: str() on a bytes instance
---> 警告信息行:  print(str(my_bytes))
b'0001'# 指定-bb选项,python产生错误信息,程序终止运行。
(py3.7_env) tony@ubtu-nas918:~$ python -bb mybytes.py
my_bytes type is: <class 'bytes'>
---> 错误信息行:Traceback (most recent call last):
---> 错误信息行:  File "mybytes.py", line 4, in <module>
---> 错误信息行:    print(str(my_bytes))
---> 错误信息行:BytesWarning: str() on a bytes instance

-B选项

-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x

在导入Python脚本时,不保存.pyc文件;等价于环境变量PYTHONDONTWRITEBYTECODE=x

下面的例子,在未指定-B选项时,在执行__main__.py脚本时,会在当前目录下创建__pycache__子目录,在该目录下保存生成的.pyc文件。

(py3.7_env) tony@ubtu-nas918:~$ cat __main__.py
print("Hello, Python!")(py3.7_env) tony@ubtu-nas918:~$ python .
Hello, Python!# 生成的__pycache__子目录
(py3.7_env) tony@ubtu-nas918:~$ ls
__main__.py __pycache__/ # 保存的.pyc文件:
(py3.7_env) tony@ubtu-nas918:~$ ls -l __pycache__
total 4
-rw-rw-r-- 1 tony tony 128 Mar 29 14:13 __main__.cpython-37.pyc

如果在执行Python脚本时,指定了-B选项,则仅执行这个脚本,不会保存.pyc文件。
如果定义了环境变量PYTHONDONTWRITEBYTECODE=x,也不会保存.pyc文件。

(py3.7_env) tony@ubtu-nas918:~/opt-B$ cat __main__.py
print("Hello, Python!")# 使用-B选项,期望不生成__pycache__目录以及.pyc文件
(py3.7_env) tony@ubtu-nas918:~/opt-B$ python -B .
Hello, Python!# 没有生成__pycache__目录
(py3.7_env) tony@ubtu-nas918:~/opt-B$ ls
__main__.py# 设置环境变量
(py3.7_env) tony@ubtu-nas918:~$ export PYTHONDONTWRITEBYTECODE=x# 未指定-B选项,但是设置了环境变量
(py3.7_env) tony@ubtu-nas918:~/opt-B$ python .
Hello, Python!# 依然没有生产__pycache__目录以及.pyc文件
(py3.7_env) tony@ubtu-nas918:~/opt-B$ ls
__main__.py

-d选项

-d     : debug output from parser; also PYTHONDEBUG=x

打印parser产生的调试信息;等价于环境变量PYTHONDEBUG=x

-E选项

-E     : ignore PYTHON* environment variables (such as PYTHONPATH)

忽略PYTHON*环境变量(例如PYTHONPATH)

-h / -? / --help选项

-h     : print this help message and exit (also --help)

打印出帮助信息,然后退出。(也支持--help。)

-i选项

-i     : inspect interactively after running script; forces a prompt evenif stdin does not appear to be a terminal; also PYTHONINSPECT=x

在运行脚本后,进入交互式检查;即便是标准输入不是终端,也显示提示符。等价于环境变量PYTHONINSPECT=x。

# 在Python脚本运行结束后,获得了>>>提示符,可以继续输入并执行python语句
(py3.7_env) tony@ubtu-nas918:~$ python -i hello3.py
Hello, world
Hello, Python!
10
>>> print(s)
Hello, world
>>>

-I选项

-I     : isolate Python from the user's environment (implies -E and -s)

将Python与用户的环境隔离(隐含-E与-s选项)

-O与-OO选项

-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

-O:删掉assert与__debug__依赖的语句;在保存的.pyc文件扩展名之前,添加.opt-1字样;等价于PYTHONOPTMIZE=x
-OO:执行-O的动作,额外还会丢掉docstrings;在.pyc文件扩展名之前,添加.opt-2字样

(py3.7_env) tony@ubtu-nas918:~/opt-B$ python -O .
Hello, Python!(py3.7_env) tony@ubtu-nas918:~/opt-B$ python -OO .
Hello, Python!# 生成的.pyc文件扩展名前,添加了.opt-1与.opt-2
(py3.7_env) tony@ubtu-nas918:~/opt-B$ ls __pycache__/
__main__.cpython-37.opt-1.pyc  __main__.cpython-37.opt-2.pyc  __main__.cpython-37.pyc

-q选项

-q     : don't print version and copyright messages on interactive startup

在交互启动时,不打印版本与版权信息

# 未指定-q选项,交互执行时,先打印版本与版权信息
(py3.7_env) tony@ubtu-nas918:~/opt-B$ python
Python 3.7.3 (default, Mar 26 2019, 01:59:45)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>># 指定-q选项,立即显示命令提示符>>>
(py3.7_env) tony@ubtu-nas918:~/opt-B$ python -q
>>>

-s选项

-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE

不向sys.path中添加用于站点目录;等价于PYTHONNOUSERSITE。

-S选项

-S     : don't imply 'import site' on initialization

在初始化时,不要执行’import site’。测试了一下效果就是

# 指定-S选项
tony@ubtu-nas918:~/opt-B$ python3.7 -S
Python 3.7.3 (default, Mar 26 2019, 01:59:45)
[GCC 5.4.0 20160609] on linux
>>> help(quit) # 没有help可用
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'help' is not defined
>>> quit() # 没有quit()可用
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'quit' is not defined
>>> import sys
>>> sys.path # sys.path少了几个目录
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload']
>>>  # <CTRL+D>退出Python# 正常启动时的sys.path目录
tony@ubtu-nas918:~/opt-B$ python3.7
Python 3.7.3 (default, Mar 26 2019, 01:59:45)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']

-u选项

-u     : force the stdout and stderr streams to be unbuffered;this option has no effect on stdin; also PYTHONUNBUFFERED=x

强制标准输出stdout与标准输入stderr流是无缓冲的;这个选项对标准输入stdin无效;等价于环境变量PYTHONUNBUFFERED=x

-v选项

-v     : verbose (trace import statements); also PYTHONVERBOSE=xcan be supplied multiple times to increase verbosity

冗余输出(用于跟踪import语句);等价于PYTHONVERBOSE=x
可以多次使用增加跟踪冗余度。

-V / --version选项

-V     : print the Python version number and exit (also --version)when given twice, print more information about the build

打印Python版本号,然后退出(即–version)。当使用-VV时,会打印出更多信息。

# 打印版本号
(py3.7_env) tony@ubtu-nas918:~$ python -V
Python 3.7.3# 打印更多信息
(py3.7_env) tony@ubtu-nas918:~$ python -VV
Python 3.7.3 (default, Mar 26 2019, 01:59:45)
[GCC 5.4.0 20160609]# 不报错,与-VV等价
(py3.7_env) tony@ubtu-nas918:~$ python -VVV
Python 3.7.3 (default, Mar 26 2019, 01:59:45)
[GCC 5.4.0 20160609]

-W arg选项

-W arg : warning control; arg is action:message:category:module:linenoalso PYTHONWARNINGS=arg

警告控制;参数是action:message:category:module:lineno;等价于环境变量PYTONWARNINGS=arg
arg的选项很多,常用的包括

  • ignore:忽略所有警告信息
  • default:明确地设置为默认警告信息
  • all:每次出现警告信息都打印(小心:如果在某个循环中产生了警告,则可能会产生许多信息)
  • module:模块产生的警告信息,只在第一次发生时打印
  • once:程序产生的警告信息,只在第一次发生时打印
  • error:把警告信息当作错误。

完整的arg格式是:action:message:category:module:line,详情参看Python文档。

-x选项

-x     : skip first line of source, allowing use of non-Unix forms of #!cmd

略过Python源文件的第一行,允许使用非UNIX格式#!cmd。

-X opt选项

-X opt : set implementation-specific option

设置特定实现上的选项。详情参看:https://docs.python.org/zh-cn/3/using/cmdline.html

–check-hash-based-pycs always|default|never选项

--check-hash-based-pycs always|default|never:control how Python invalidates hash-based .pyc files

只是Python如何使基于哈希的.pyc文件无效。有三种选择:

  • default:对checked与unchecked的基于哈希的字节码缓存文件,按照默认的语义验证有效性
  • always:所有基于哈希的.pyc文件,无论是checked还是unchecked,都与相应的源代码比较来验证有效性。
  • never:所有基于哈希的.pyc文件,都不与相应的源代码比较来验证有效性。

这个选项并不影响基于时间戳的.pyc文件的有效性验证方法。

参考

Python 3.7.3的完整命令行参数里列表

C:\Users\tsu5>py -3 --help
usage: C:\Python\Python3.7.3\python.exe [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 evenif 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=xcan 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:linenoalso PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--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 thedefault module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>;<exec_prefix>).The default module search path uses <prefix>\python{major}{minor}.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
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 usedto seed the hashes of str, bytes and datetime objects.  It can also beset to an integer in the range [0,4294967295] to get hash values with apredictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hookson Python memory allocators. Use PYTHONMALLOC=debug to install debughooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the localecoercion behavior. Use PYTHONCOERCECLOCALE=warn to request display oflocale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the defaultdebugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.

【Python】Python3.7.3 - Python命令行参数详解相关推荐

  1. Python 命令行参数详解

    Python 命令行参数详解 0. 命令行参数 1. sys.argv 2. getopt 2.1 getopt.getopt 方法 2.2 Exception getopt.GetoptError ...

  2. python编写命令行框架_python的pytest框架之命令行参数详解(上)

    前言 pytest是一款强大的python自动化测试工具,可以胜任各种类型或者级别的软件测试工作.pytest提供了丰富的功能,包括assert重写,第三方插件,以及其他测试工具无法比拟的fixtur ...

  3. 【linux】Valgrind工具集详解(八):Memcheck命令行参数详解

    [linux]Valgrind工具集详解(五):命令行详解中不够全,在此专门针对Memcheck工具中的命令行参数做一次详细的解释. Memcheck命令行选项 –leak-check=<no| ...

  4. [OpenAirInterface实战-11] :OAI nr-softmodem命令行参数详解

    作者主页(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客 本文网址:https://blog.csdn.net/HiWangWenBing/article/detai ...

  5. UltraISO命令行参数详解

    UltraISO 命令行参数 命名行参数说明 参数 说明 -volume string 卷标签 -sysid string 系统 ID -appid string 应用程序 ID -volset st ...

  6. C语言命令行参数详解

    C语言的main函数通常含有参数argc和argv,写法通常如下: int main(int argc,char *argv[]) int main(int argc,char **argv) 下面详 ...

  7. java命令行参数详解

    java 命令参数详解_赶路人儿的博客-CSDN博客_java命令行参数java命令用于启动 java 应用:它首先会启动 java 运行时环境(JRE),然后加载指定的类,调用类的main()方法. ...

  8. 7z命令行参数详解--python暴破压缩文件命令必备

    7z.exe在CMD窗口的使用说明如下: 7-Zip (A) 4.57 Copyright (c) 1999-2007 Igor Pavlov 2007-12-06 Usage: 7za <co ...

  9. Beeline – 命令行参数详解

    Beeline Shell 在嵌入式模式和远程模式下均可工作.在嵌入式模式下,它运行嵌入式 Hive(类似于Hive CLI),而远程模式用于通过 Thrift 连接到单独的 HiveServer2 ...

最新文章

  1. android 定义date对象,如何从Date对象设置Android Chronometer基准时间?
  2. iOS开发系列--并行开发其实很容易
  3. 庖丁解牛TLD(一)——开篇
  4. 2020CCPC绵阳
  5. 前端学习(3030):vue+element今日头条管理-顶部导航栏布局
  6. 【狂神说】分析前后端分离开源项目?
  7. 实时媒体AI,打破内容创作天花板,加速视频创新
  8. shiro利用mysql动态授权_SpringBoot+Shiro学习之数据库动态权限管理和Redis缓存
  9. 软件质量模型的6大特性27个子特性
  10. python实现连接池技术
  11. 基于视频会议系统的应急指挥项目建设方案
  12. 1.1、信息化和信息系统
  13. python 调用淘宝客api
  14. 强行调用html5,Html5踩坑记之mandMobile使用小记
  15. oracle latch chain,Oracle Latch及latch矛盾
  16. __bridge,__bridge_transfer和__bridge_retained详解
  17. Python 三大利器:迭代器、生成器、装饰器
  18. DJ2-2 进程管理
  19. PHP CURL解决 此图片来自QQ微信公众平台,未经允许不可引用
  20. 他们如何利用微信赚钱

热门文章

  1. git clone --depth=1 -b 4.24
  2. poj 2031 BuildingaSpaceStation 最小生成树 Prim、Kruskal
  3. db2 兼容 oracle 语法,db2 case when和oracle兼容有关问题
  4. ubuntu 14.10 64bit系统安装MBuntu主题(仿Mac主题)
  5. 例子---PHP与Form表单之二
  6. python加载模型_解决python 无法加载downsample模型的问题
  7. foreach循环符合就不往下走了_Java基础入门篇——For循环
  8. python编程一球从100米_Python练习题 015:一颗自由落地的球
  9. 西铁院云计算机室与应用,关于开展“云桌面应用”技术服务的通知
  10. docker 管理工具_详解Docker可视化管理工具shipyard--部署教程及功能展示