python -c 的学习使用

一、参数介绍

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

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值