运行 在 Python 中使用子进程的 shell 脚本不产生输出

Running a shell script using Subprocess in Python does not produce output

我正在尝试 运行 使用 Python 使用 subprocess.Popen() 的 shell 脚本。

shell 脚本只有以下几行:

#!/bin/sh
echo Hello World

以下是Python代码:

print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
shellscript.wait()

for line in shellscript.stdout.readlines():
    print(line)
print("SHELL SCRIPT RUN ENDED")

但是,在 运行 上,我只得到以下输出:

RUNNNING SHELL SCRIPT NOW
SHELL SCRIPT RUN ENDED

即我没有在这两行之间得到 shell 脚本输出。

此外,当我从子进程中删除 stderr=subprocess.PIPE 部分时,我得到以下输出:

RUNNNING SHELL SCRIPT NOW
'km' is not defined as an internal or external command.
SHELL SCRIPT RUN ENDED

我无法理解如何解决这个问题,并且 运行 shell 脚本正确。请指导。谢谢。

更新:

我还尝试了以下更改:

print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

out, err = shellscript.communicate()
print(out)
print("SHELL SCRIPT RUN ENDED")

我得到以下输出:

RUNNNING SHELL SCRIPT NOW
b''
SHELL SCRIPT RUN ENDED

简单直接的解决方法是不要为此使用裸 Popen

您也不需要 shell 到 运行 子流程;如果子进程是一个 shell 脚本,那么子进程本身就是一个 shell,但是你不需要 shell 到 运行 的帮助那个脚本。

proc = subprocess.run(
    ['km/example/example1/source/test.sh'],
    check=True, capture_output=True, text=True)
out = proc.stdout

如果你真的需要使用Popen,你需要了解它的处理模型。但如果您只是想完成工作,简单的答案是不要使用 Popen.

错误消息实际上看起来像你在 Windows,它试图通过 cmd 运行 km 认为斜杠是选项分隔符,而不是目录分隔符。删除 shell=True 避免了这种复杂化,并且只用请求的名称启动一个进程。 (当然,这仍然要求文件存在于您指定的相对文件名中。也许另请参阅 并且可能切换到本机 Windows 反斜杠,使用 r'...' 字符串以防止Python 试图解释反斜杠。)