首页 > 解决方案 > Subprocess.Popen doesnt finish the called script

问题描述

My goal is to call a different python script by using subprocess.Popen and save the results inside of a txt file. I used

process = subprocess.Popen("start cmd /c abq2020 python " + directory + os.sep + "data_mean.py", shell=True)
process.wait()

file = np.loadtxt(directory + os.sep + 'Values.txt')

in my main program and

f = open(varpath + os.sep + 'Values.txt','w+')

for i in Output:
    for j in i:
        f.write(str(j) + '     ')
    f.write('\n')
    
f.close()

in the subprogram.

Now my problem is that the main program won't wait until the subprogram created the txt file and thus produces an error message.

I used this method because I dont know an other way to pass variables between the main and the sub process. I appreciate any ideas and advices.

Thanks in advance.

标签: pythonsubprocess

解决方案


I don't know what apq2020 is and why it is preceding the python command, but I assume you know what you are doing. You do not need to nor should you be starting up a command prompt. This is all you should need in addition to providing lots of missing import statements:

process = subprocess.Popen("abq2020 python " + directory + os.sep + "data_mean.py", shell=True)
process.communicate() # process.wait() will work in this case, too

file = np.loadtxt(directory + os.sep + 'Values.txt')

推荐阅读