一、参数介绍
python的 -c
可以在命令行中调用 python 代码, 实际上 -c 就是 command 的意思,简单来说, 就是 python -c
可以在命令行中执行 python 代码, 跟把代码放置在 .py 文件中然后运行这个文件比无明显差别
二、使用说明
需要注意的是, python -c 后必须跟一个字符串, 因此必须带上引号
2.1、单行命令
python -c print(123)
bash: syntax error near unexpected token `('
python -c print 123 #没有回显
python -c "print(123)"
123
python -c "print("python")"
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'python' is not defined
python -c '''print("python")'''
python
综上,python -c必须加引号,且建议使用三引号
2.2、多行命令
# 多行写一行,缩进不考虑
python -c '''if 5 > 3: print "yes"'''
yes
# 加换行缩进
python -c '''
> if 5 > 3:
> print "yes"
> '''
File "<string>", line 3
print "yes"
^
IndentationError: expected an indented block
python -c '''
if 5 > 3:
print "yes"
'''
yes
# 多行时必须严格控制缩进
2.3、多个语句之间用;
隔开
python -c '''print 5; print 3'''
5
3
三、妙用
参考:https://www.cnblogs.com/chnmig/p/14207100.html
四、参考文档
1、https://blog.csdn.net/phoenix339/article/details/90405610
2、https://www.cnblogs.com/chnmig/p/14207100.html
3、https://docs.python.org/3/using/cmdline.html#cmdoption-c