【Python】Python3.7.3 - Python命令行参数详解

Python 专栏收录该内容
19 篇文章 0 订阅

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/python3

print("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!")
EOF

Hello, 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.py

my_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 even
         if 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=x
         can 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:lineno
         also 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 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
--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>\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 used
   to seed the hashes of str, bytes and datetime 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.
  • 1
    点赞
  • 0
    评论
  • 6
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值