2014-10-13 29 views
0

我在这里遇到一些问题,试图使用subprocess.Popen。我不能使用subprocess.Call来编写我正在编写的脚本,因为我希望能够为我的执行指定环境,而我只能通过方法的参数在Popen中这样做。我注意到subprocess.Popen需要更长的时间来完成该子进程。调用,并且这在我的脚本中产生了下游问题,因为我的脚本的其余部分依赖于产生的进程的退出代码(返回代码)来决定(通过一组有条件的If语句)进行适当的操作。如何确保脚本仅在子进程完成后执行后续方法

涉及使用子过程的方法是:

def execute_local(self): 
''' 
Spawns a test execution process locally and directs the standard output and 
error streams from the process to the appropriate log files. 
''' 
self.return_code = subprocess.Popen(args = self.cmd_string, 
            stdout = open(self.out_log_filepath, 'w'), 
            stderr = open(self.err_log_filepath, 'w'), 
            shell = True) 

我还没有指定的ENV参数还没有,因为我需要确保这个工程之前,我可以继续前进。

和包含该条件语句后续方法是:

def get_status(self): 
''' 
Returns a string named either passed or failed back to itself, depending on 
exit status of the process that was spawned in the execute_local method. 

This is important for main.py to be able to examine the status of the test 
processes and take appropriate administrative actions to either continue to 
a new test step or retry a give test. 
''' 
print self.return_code 
if self.return_code == 0: 
    return 'passed' 
else: 
    return 'failed' 

在更高层次的模块,所述方法将被称为按照以下顺序:execute_local ---接着----> GET_STATUS。

此前,当我通过调用完成此操作时,执行过程顺利进行到条件,但现在与Popen不同。当我尝试使用print语句打印出由子进程产生的进程的返回代码时(我在get_status方法中添加了print self.return_code语句,如下所示),我发现通过调用,我实际看到返回代码,但与Popen,我得到的是对象本身和它的内存地址。

我非常感谢这方面的帮助,如果有人能向我解释为什么Popen比打电话要花更多时间才能跑步。

非常感谢!

回答

1

subprocess.call只是一个围绕Popen的包装,它等待被调用的进程退出。它采用与Popen相同的参数,可以替换(错误执行)Popen,并用call替换它以获得所需内容。

self.return_code = subprocess.call(args = self.cmd_string, 
            stdout = open(self.out_log_filepath, 'w'), 
            stderr = open(self.err_log_filepath, 'w'), 
            shell = True, 
            env=my_env) 

在您当前的实现中,您返回的是Popen对象,而不是返回码。

+0

非常感谢您的回答!这澄清。我认为他们应该在Pydocs中加入env参数(以及所有其他参数),否则它会使得看起来好像call缺少Popen所具有的某些功能。 – AKKO

相关问题