我有一个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
(跳过了这里的许多其他代码)
if __name__ == '__main__':
#self-test code
pipelineObj = Pipeline(sys.argv)
pipelineObj.setupPipeline()
然而,当代码到达第二个命令,我收到了
IOError: [Errno 32] Broken pipe
如何重新使用子进程对象发出需要在同一个shell中执行的命令?这些命令不能简单地链接在一起,因为每次调用之间正在进行处理。
(一)你为什么要一遍又一遍地重复使用相同的壳呢? (b)为什么你必须使用shell?您可以简单地[直接使用数组来执行这些命令以将参数拆分](http://docs.python.org/library/subprocess.html#subprocess.Popen) - 并确信PATH也不会IFS环境变量会影响程序的执行。 – sarnold
因为每个命令的结果都需要影响后续命令的shell环境。 –