是否有 Python 参数可以在不启动交互式解释器或从文件读取的情况下从 shell 执行代码?类似于:
perl -e 'print "Hi"'
这有效:
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).
另一种方法是使用 bash 重定向:
python <<< 'print "Hi"'
这也适用于 perl、ruby 等等。
ps
要为 python 代码保存引号 ' 和 ",我们可以使用 EOF 构建块
c=`cat <<EOF
print(122)
EOF`
python -c "$c"
' 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