python3 -c command 介绍

2021-04-23  本文已影响0人  tafanfly

python -c command 含义

使用 python -h,查看 -c 参数的说明: -c cmd : program passed in as string (terminates option list)

意思是用 -c command 调用时,执行 command 表示的 Python 语句。command 可以包含用换行符;分隔的多条语句。

简单来说就是在命令行执行python代码

python -c command举例应用

$ python -c "import time;print(time.time());print('That is OK.')"
1618970995.6005359
That is OK.

$ python -c "import sys;print(sys.path);print(sys.argv)" a b d
['', '/home/tafan/workspace/envs/python_3_6/lib/python36.zip', '/home/tafan/workspace/envs/python_3_6/lib/python3.6', '/home/tafan/workspace/envs/python_3_6/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/tafan/workspace/envs/python_3_6/lib/python3.6/site-packages']
['-c', 'a', 'b', 'd']

$ python -c "for i in range(3):
    print(i)
    print('OK')"
0
OK
1
OK
2
OK

$ python -c "for i in range(3):
 print(i)
print('OK')"
0
1
2
OK

 $ python -c "for i in range(3):print(i)"
0
1
2

由上面的测试代码可知:

python -c command意义

-c 参数提供了不进入python解释器的交互模式,就能够执行python代码的方式。这种方式执行python代码,所有的输出都在命令行,也许在某些shell脚本的场景下会很有用。

参考:
https://docs.python.org/zh-cn/3/using/cmdline.html#cmdoption-c
https://www.pynote.net/archives/1741

上一篇 下一篇

猜你喜欢

热点阅读