简体   繁体   English

重用子流程对象

[英]Reusing subprocess object

I have a Python script that needs to issue a number of shell commands.我有一个 Python 脚本需要发出许多 shell 命令。 I thought I could just create a subprocess object and then reuse it each time I had a command to execute.我以为我可以只创建一个子进程对象,然后在每次有命令要执行时重用它。

This is how I have my code set up:这就是我设置代码的方式:

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

(skip a lot of other code here) (这里跳过很多其他代码)

if __name__ == '__main__':
#self-test code
pipelineObj = Pipeline(sys.argv)
pipelineObj.setupPipeline()

However, when the code gets to the second command I get a但是,当代码到达第二个命令时,我得到一个

IOError: [Errno 32] Broken pipe

How do I go about reusing a subprocess object to issue commands that need to all execute within the same shell?我如何着手重用子进程对象来发出需要在同一个 shell 中全部执行的命令? These commands can't be simply chained together since there is processing going on in between each call.这些命令不能简单地链接在一起,因为在每次调用之间都在进行处理。

Create a subprocess that executes a shell, and send commands to that.创建一个执行 shell 的子进程,并向其发送命令。 You're running an empty command in the shell, which causes it to execute that empty command and then exit.shell 中运行一个空命令,这导致它执行该空命令然后退出。

shell = subprocess.Popen("/bin/bash -i".split(), stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)

You might instead consider using pexpect as it sounds like you are well on your way to reinventing it.您可能会考虑使用pexpect ,因为听起来您正在重塑它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM