从 Python 子进程执行 shell 脚本 [英] execute a shell-script from Python subprocess
问题描述
我需要从 python 调用一个 shellscript.问题是 shellscript 会一路问几个问题,直到它完成.
I need to call a shellscript from python. The problem is that the shellscript will ask a couple of questions along the way until it is finished.
我找不到使用 subprocess
的方法!(使用 pexpect
似乎有点过头了,因为我只需要启动它并向它发送几个 YES)
I can't find a way to do so using subprocess
! (using pexpect
seems a bit over-kill since I only need to start it and send a couple of YES to it)
请不要建议需要修改 shell 脚本的方法!
推荐答案
使用 subprocess
库,你可以告诉 Popen
类你想管理标准输入过程如下:
Using the subprocess
library, you can tell the Popen
class that you want to manage the standard input of the process like this:
import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)
现在 shellscript.stdin
是一个类似文件的对象,您可以在其上调用 write
:
Now shellscript.stdin
is a file-like object on which you can call write
:
shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait() # blocks until shellscript is done
您还可以通过设置 stdout=subprocess.PIPE
和 stderr=subprocess.PIPE
来从进程中获取标准输出和标准错误,但是您不应该使用 PIPEs
用于标准输入和标准输出,因为可能导致死锁.(请参阅文档.)如果您需要输入和输出,请使用communicate
方法而不是类似文件的对象:
You can also get standard out and standard error from a process by setting stdout=subprocess.PIPE
and stderr=subprocess.PIPE
, but you shouldn't use PIPEs
for both standard input and standard output, because deadlock could result. (See the documentation.) If you need to pipe in and pipe out, use the communicate
method instead of the file-like objects:
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
这篇关于从 Python 子进程执行 shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!