首页 > 解决方案 > Python子进程在交互模式下工作但不在脚本中

问题描述

我正在尝试从 python 执行 shell 脚本并捕获输出。

我正在使用以下几行:

x = subprocess.run(["sh", "/path/to/script/myscript.bash"], stdout=subprocess.PIPE)
print(x.stdout.decode('utf8'))

这在 python 交互模式下运行时工作正常,但在 python 脚本中执行时它只是挂起,我必须使用 ctrl+Z 来终止 python 脚本。我错过了什么?

在过去使用 python 2.7 时,我刚刚使用了如下一行:

x = subprocess.Popen(args='sh /path/to/script/myscript.bash', stdout=subprocess.PIPE, shell=True) 
scriptOutput = str(x.communicate()[0])

这似乎不适用于我正在运行的 python 3.6。

标签: pythonsubprocesssh

解决方案


推荐阅读