phi*_*ogg 1 python shell subprocess
我有一个 Python 脚本,需要发出许多 shell 命令。我认为我可以创建一个子进程对象,然后在每次执行命令时重用它。
这就是我设置代码的方式:
def setupPipeline(self):
setupShell = subprocess.Popen([''], stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# Stop running pipeline
setupShell.stdin.write('stop ' + self.Name)
output = setupShell.stdout.read()
print output
# Cancel any running jobs and cleanup variables
setupShell.stdin.write('sudo -u pr cancel ALL')
output = setupShell.stdout.read()
print output
setupShell.stdin.write('sudo -u pr clean ALL')
output = setupShell.stdout.read()
print output
Run Code Online (Sandbox Code Playgroud)
(这里跳过很多其他代码)
if __name__ == '__main__':
#self-test code
pipelineObj = Pipeline(sys.argv)
pipelineObj.setupPipeline()
Run Code Online (Sandbox Code Playgroud)
但是,当代码到达第二个命令时,我得到一个
IOError: [Errno 32] Broken pipe
Run Code Online (Sandbox Code Playgroud)
如何重用子进程对象来发出需要在同一 shell 中执行的命令?这些命令不能简单地链接在一起,因为每次调用之间都会进行处理。
创建一个执行 shell 的子进程,并向其发送命令。您正在 shell中运行一个空命令,这会导致它执行该空命令然后退出。
shell = subprocess.Popen("/bin/bash -i".split(), stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
您可能会考虑使用pexpect,因为听起来您正在重新发明它。