从Python子进程执行shell脚本

the*_*lse 3 python subprocess pexpect

我需要从python调用一个shellcript.问题是,shellcript会在完成之前一直提出几个问题.

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

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

Jim*_*ski 5

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

import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

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

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()   # blocks until shellscript is done
Run Code Online (Sandbox Code Playgroud)

您还可以通过设置stdout=subprocess.PIPE和从过程中获得标准输出和标准错误stderr=subprocess.PIPE,但不应该同时使用PIPEs标准输入和标准输出,因为可能会导致死锁.(请参阅文档.)如果需要管道输入和管道输出,请使用该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
Run Code Online (Sandbox Code Playgroud)