c调用python参数_用-c参数在命令行执行python代码

python解释器的 -c 选项,表示将后面的输入作为cmd来执行。cmd其实就是python的语句(statement)。所以,这就是在命令行执行python代码!

使用 python -h,查看 -c 参数的说明:

-c cmd : program passed in as string (terminates option list)

官方文档对python -c还有一段说明:

-c

Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.

If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to the start of sys.path (allowing modules in that directory to be imported as top level modules).

Raises an auditing event cpython.run_command with argument command.

下面举例,注意多行python代码要换行,也可以按照python语法使用分号(;)

$ python3 -c "import sys; print(sys.executable)"

/usr/bin/python3

$ python3 -c "

> import random

> for i in range(10):

> print(random.randint(0,9))

> "

5

5

2

2

5

5

7

4

9

2

上面这代码测试用例,有两个细节:

1, 不能写成这样: $ python3 -c "import random; for i in .....",这样代码在python解释器中也是语法错误,分号(;)的使用不适合这样的场景;

2, for 语句后的那一行,缩进只有一个空格,代码能够正确执行;这与在exec函数中输入的代码字符串一样,在这时,4个空格的缩进不再是强制的,只要有缩进,python解释器就能够识别。

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

-- EOF --

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值