2024-06-02 10:17:40 发布
网友
我需要从python调用shell脚本。 问题是shellscript在完成之前会问几个问题。
我用subprocess找不到这样做的方法!(使用pexpect似乎有点过分了,因为我只需要启动它并向它发送几个YES)
subprocess
pexpect
请不要建议需要修改shell脚本的方法!
使用subprocess库,您可以告诉Popen类您想要管理流程的标准输入,如下所示:
Popen
import subprocess shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)
现在shellscript.stdin是一个类似文件的对象,您可以对其调用write:
shellscript.stdin
write
shellscript.stdin.write("yes\n") shellscript.stdin.close() returncode = shellscript.wait() # blocks until shellscript is done
也可以通过设置stdout=subprocess.PIPE和stderr=subprocess.PIPE从进程中获取标准输出和标准错误,但不应该对标准输入和标准输出都使用PIPEs,因为可能会导致死锁。(请参见documentation)如果需要导入和导出管道,请使用communicate方法而不是类似于文件的对象:
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
使用
subprocess
库,您可以告诉Popen
类您想要管理流程的标准输入,如下所示:现在
shellscript.stdin
是一个类似文件的对象,您可以对其调用write
:也可以通过设置
stdout=subprocess.PIPE
和stderr=subprocess.PIPE
从进程中获取标准输出和标准错误,但不应该对标准输入和标准输出都使用PIPEs
,因为可能会导致死锁。(请参见documentation)如果需要导入和导出管道,请使用communicate
方法而不是类似于文件的对象:相关问题 更多 >
编程相关推荐