等待外部启动流程产品完成继续

问题描述 投票:0回答:1

我有一个Python代码,其中定义了一些调用外部进程的函数。每个函数启动的每个进程都会生成运行下一个函数所需的最终产品。问题是脚本没有等待外部后台进程完成(我正在处理一些繁重的图像,因此该过程需要一段时间)。

我尝试使用

os.system()
subprocess.call()
subprocess.run()
启动外部进程,但没有一个起作用。我还尝试过使用
time.sleep()
Event().wait()
,但它们也不起作用,因为它们也会停止外部后台进程。

部分代码:当调用

cmd
字符串时,会向图像处理程序启动外部进程。 即使第一次调用的产品尚未完成,第二次调用
function
时也会出现错误。

问题可能在于函数中没有返回特定的产品,因此 Python 无法识别产品何时完成。

import subprocess 


def function(directory, exe, a, b):    
    cmd = directory + exe + a + b
    subprocess.run(cmd)
 

function(directory1, exe1, a1, b1)
function(directory2, exe2, a2, b2) #directory2 is where the product obtained from function1 is saved. 
function(directory3, exe3, a3, b3) #directory3 is where the product obtained from funciton2 is saved.

有没有办法停止执行以下命令,直到获得产品,而不停止后台进程?

有什么帮助吗?感谢您的任何建议!

python subprocess system-calls wait
1个回答
1
投票

subprocess.run
应该等待命令完成,然后返回。

要解决此问题,请尝试添加更多调试输出:

import subprocess 
from subprocess import PIPE


def function(directory, exe, a, b):    
    cmd = directory + exe + a + b
    print("Running", cmd)

    result = subprocess.run(cmd, stdout=PIPE, stderr=PIPE)

    print("Return code:", result.returncode)
    print("STDOUT:", result.stdout)
    print("STDERR:", result.stderr)
 

function(directory1, exe1, a1, b1)
function(directory2, exe2, a2, b2) #directory2 is where the product obtained from function1 is saved. 
function(directory3, exe3, a3, b3)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.