繁体   English   中英

如何从 bash shell 内联执行 Python

[英]How to execute Python inline from a bash shell

是否有一个 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

另一种方法是使用e模块

例如。

$ python -me 1 + 1
2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM