使用args在Python中调用子流程并读取stdout

时间:2014-09-29 17:13:32

标签: python subprocess

我尝试用Python中的另一个脚本调用一个脚本。我正在使用subprocess进行一次调用,但我不知道如何调用同一个子进程。

我有一个GUI,然后我调用我的Python脚本simulator.py。

simulator.py:

while 1:
    try:
        comando = raw_input('>> ')
        cmds = comando.split(' ')
        cmds = filter(None, cmds)

    except EOFError:
        break
    if not comando: continue
    elif cmds[0] == 'c':
        print "works first cmd"
    elif cmds[0] == 'm':
        print "works second cmd"

在我实现GUI的脚本中,当我按下“加载模拟器”按钮时,我想在子进程中启动simulator.py。使用其他按钮,我想将不同的消息发送到之前打开的同一个子进程。

#load simulator method
term = subp.Popen('python simulator.py', shell=True, stdout=subp.PIPE, stdin=subp.PIPE, stderr=subp.PIPE)
resp, error = term.communicate("c some_argument")
print resp
self.spT

#click other button method
term = self.spT
resp, error = term.communicate("m some_argument")
print resp

该代码导致错误。然后我尝试了这个:

#load simulator button method
term = subp.Popen('python simulator.py', shell=True, stdout=subp.PIPE, stdin=subp.PIPE, stderr=subp.PIPE)
term.stdin.write("c argument")
term.stdin.close()
print term.stdout.read()
self.spT = term

当我按下另一个按钮时,它会调用相同的子进程并向其发送另一个“命令”和其他参数:

#button X to send other arg to the same subprocess
term = self.spT
term.stdin.write("m argument")
term.stdin.close()
print term.stdout.read()

但这也会导致错误。我也试过了term.stdin.flushwait等等。我在互联网上尝试过一些例子。我找不到能做我想做的事。

我需要使用线程吗?我该如何实现此功能?子流程是否可以在不挂起GUI的情况下运行?我必须使用其他模块吗?

0 个答案:

没有答案