【问题标题】:How to execute Python inline from a bash shell如何从 bash shell 内联执行 Python
【发布时间】:2013-06-04 01:03:02
【问题描述】:

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

perl -e 'print "Hi"'

【问题讨论】:

  • -cman 页面中描述的第二个选项。

标签: python shell inline execution


【解决方案1】:

这行得通:

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).

【讨论】:

  • 记住您可以使用; 分隔语句也很有用,例如python -c 'import foo; foo.bar()'
  • 在 python 3.8 上对我不起作用。Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'Hi' is not defined
  • 确保“Hi”在引号中。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    python <<< 'print "Hi"'
    

    这也适用于 perl、ruby 等等。

    附言

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

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

    【讨论】:

      【解决方案4】:

      另一种方法是使用e module

      例如。

      $ python -me 1 + 1
      2
      

      【讨论】:

      • 有趣。但您需要额外安装。
      • 没用,除非你已经运行过pip install e。对于标准的 python 安装,这会产生错误:No module named e.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多