如何从bash shell执行Python内联

问题描述 投票:34回答:3

是否有Python参数从shell执行代码而无需启动交互式解释器或从文件中读取?类似的东西:

perl -e 'print "Hi"'
python shell inline execution
3个回答
82
投票

这有效:

python -c 'print("Hi")'
Hi

15
投票

另一种方法是使用bash重定向:

python <<< 'print "Hi"'

这也适用于perl,ruby和什么不是。

附:

为了保存引号'和'对于python代码,我们可以使用EOF构建块

c=`cat <<EOF
print(122)
EOF`
python -c "$c"

2
投票

另一种方法是使用e module

例如。

$ python -me 1 + 1
2
© www.soinside.com 2019 - 2024. All rights reserved.