【问题标题】:Python Running Bash Script and Getting OutputPython 运行 Bash 脚本并获取输出
【发布时间】:2021-07-13 13:34:49
【问题描述】:

我需要运行一个 bash 脚本并获取输出。该脚本有一个带有变量的循环。

当我仅粘贴 bash 脚本时它在终端屏幕上工作,但当我使用 Python 使用子进程时它会出错。代码如下:

import subprocess

text1 = """
declare -a StringArray=("a1" "a2" "a3" "a4" "a5" )
for val in ${StringArray[@]}; do
   echo $val
done
"""
text_output = (subprocess.check_output(text1, shell=True).strip()).decode()

这是错误:

/bin/sh: 2: Syntax error: "(" unexpected
Traceback (most recent call last):
.
.
.
' returned non-zero exit status 2.

解决办法是什么?

Python3.7, OS: Debian-like Linux, Kernel: 4.19.

【问题讨论】:

    标签: python python-3.x bash terminal subprocess


    【解决方案1】:

    在这种情况下,您可以使用 subprocess.Popen

    以下是可以帮助您实现上述目标的代码。如果您有任何问题,请告诉我。

    >>> import subprocess
    >>> cmd = 'declare -a StringArray=("a1" "a2" "a3" "a4" "a5" );for val in ${StringArray[@]}; do echo $val; done'
    >>> x=subprocess.Popen(cmd,shell=True)
    >>> a1
    a2
    a3
    a4
    a5
    

    【讨论】:

    • 它不适用于 /bin/sh: 1: Syntax error: "(" unexpected 错误。
    【解决方案2】:

    错误消息指出:/bin/sh ...。 Python 没有像您期望的那样使用bash。它使用另一个外壳。 (在我的系统上shdash。)而且这个其他shell 似乎不支持StringArray=("a1" "a2" "a3" "a4" "a5" ) 语法。

    您可以尝试像这样显式选择bash

    subprocess.check_output(text1, shell=True, executable='/bin/bash')
    

    (至少,/bin/bash 可以在我的系统上运行。)

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多