我需要从 python 调用 shell 脚本。
问题是 shell 脚本在完成之前会问几个问题。
我找不到使用的方法subprocess
! (使用pexpect
似乎有点过头了,因为我只需要启动它并向它发送几个“是”)
请不要建议需要修改 shell 脚本的方法!
使用subprocess
图书馆,你可以告诉Popen
您想要管理流程的标准输入的类,如下所示:
import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)
Now shellscript.stdin
是一个类似文件的对象,您可以调用它write
:
shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait() # blocks until shellscript is done
您还可以通过设置从进程中获取标准输出和标准错误stdout=subprocess.PIPE
and stderr=subprocess.PIPE
,但你不应该使用PIPEs
对于标准输入和标准输出,因为可能会导致死锁。 (参见文档 http://docs.python.org/2.7/library/subprocess.html.) 如果您需要管道输入和管道输出,请使用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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)