95

是否有 Python 参数可以在不启动交互式解释器或从文件读取的情况下从 shell 执行代码?类似于:

perl -e 'print "Hi"'
4

4 回答 4

169

这有效:

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

从手册中,man python

   -c command
          Specify  the command to execute (see next section).  This termi-
          nates the option list (following options are passed as arguments
          to the command).
于 2013-06-04T01:07:14.117 回答
32

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

python <<< 'print "Hi"'

这也适用于 perl、ruby 等等。

ps

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

c=`cat <<EOF
print(122)
EOF`
python -c "$c"
于 2013-06-05T10:53:11.523 回答
17

' heredoc ' 可用于直接将脚本输入 python 解释器:

python <<HEREDOC
import sys
for p in sys.path:
  print(p)
HEREDOC


/usr/lib64/python36.zip
/usr/lib64/python3.6
/usr/lib64/python3.6/lib-dynload
/home/username/.local/lib/python3.6/site-packages
/usr/local/lib/python3.6/site-packages
/usr/lib64/python3.6/site-packages
/usr/lib/python3.6/site-packages
于 2019-11-13T09:12:19.700 回答
1

另一种方法是使用e模块

例如。

$ python -me 1 + 1
2
于 2013-06-04T01:24:33.380 回答