如何从 bash shell 内联执行 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16908236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute Python inline from a bash shell
提问by Sean
Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file? Something similar to:
是否有一个 Python 参数可以在不启动交互式解释器或从文件中读取的情况下从 shell 执行代码?类似于:
perl -e 'print "Hi"'
采纳答案by Mike Müller
This works:
这有效:
python -c 'print("Hi")'
Hi
回答by michaelmeyer
Another way is to you use bash redirection:
另一种方法是使用 bash 重定向:
python <<< 'print "Hi"'
And this works also with perl, ruby, and what not.
这也适用于 perl、ruby 等等。
p.s.
ps
To save quote ' and " for python code, we can build the block with EOF
为了保存 Python 代码的引用 ' 和 ",我们可以使用 EOF 构建块
c=`cat <<EOF
print(122)
EOF`
python -c "$c"
回答by awltux
A 'heredoc' can be used to directly feed a script into the python interpreter:
' 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

