从Python子进程执行shell脚本

2024-06-02 10:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从python调用shell脚本。 问题是shellscript在完成之前会问几个问题。

我用subprocess找不到这样做的方法!(使用pexpect似乎有点过分了,因为我只需要启动它并向它发送几个YES)

请不要建议需要修改shell脚本的方法!


Tags: 方法脚本shell建议yespexpectsubprocess过分
1条回答
网友
1楼 · 发布于 2024-06-02 10:17:40

使用subprocess库,您可以告诉Popen类您想要管理流程的标准输入,如下所示:

import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)

现在shellscript.stdin是一个类似文件的对象,您可以对其调用write

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()   # blocks until shellscript is done

也可以通过设置stdout=subprocess.PIPEstderr=subprocess.PIPE从进程中获取标准输出和标准错误,但不应该对标准输入和标准输出都使用PIPEs,因为可能会导致死锁。(请参见documentation)如果需要导入和导出管道,请使用communicate方法而不是类似于文件的对象:

shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = shellscript.communicate("yes\n")   # blocks until shellscript is done
returncode = shellscript.returncode

相关问题 更多 >