Python subprocess.call不等待命令执行

0 投票
2 回答
3274 浏览
提问于 2025-04-17 21:40

我刚开始学Python,因为我需要用它来完成一个课程作业。我在Freemat / octave / matlab中开发了一个解决方案(一个优化算法),并想从Python中调用它(这个Python代码会被一个评分的Python脚本调用)。

这个.m文件会读取一个叫做tmp.data的文件,并把结果写入output.txt。然后,Python脚本应该从这个输出文件中读取数据,并把它转换成评分脚本所期待的结果。

一切都运行得很好,除了我还没能让Python等Matlab完成调用,这导致后面的代码出错。

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from collections import namedtuple
Item = namedtuple("Item", ['index', 'value', 'weight'])

import subprocess
import os
from subprocess import Popen, PIPE

def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # Write the inputData to a temporay file
    tmp_file_name = 'tmp.data'
    tmp_file = open(tmp_file_name, 'w')
    tmp_file.write(input_data)
    tmp_file.close()

    # call matlab (or any other solver)
    # subprocess.call('matlab -r gp(\'tmp.data\')', shell=1)
    # run=os.system
    # a=run('matlab -r gp(\'tmp.data\')')
    # process = Popen('matlab -r gp(\'tmp.data\')', stdout=PIPE)
    # Popen.wait()
    # (stdout, stderr) = process.communicate()
    subprocess.call('matlab -r gp(\'tmp.data\')',shell=0)

    # Read result from file
    with open('output.txt') as f:
        result = f.read()

    # remove the temporay file
    os.remove(tmp_file_name)
    os.remove('output.txt')

    return result




    # return stdout.strip()



    # prepare the solution in the specified output format
    # output_data = str(value) + ' ' + str(0) + '\n'
    # output_data += ' '.join(map(str, taken))
    # return output_data


import sys

if __name__ == '__main__':
    if len(sys.argv) > 1:
        file_location = sys.argv[1].strip()
        input_data_file = open(file_location, 'r')
        input_data = ''.join(input_data_file.readlines())
        input_data_file.close()
        print solve_it(input_data)
    else:
        print 'This test requires an input file.  Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)'

如你所见,我尝试了subprocess.call、popen、os.system等方法,但都没有成功。它们都给我类似的错误:

C:\Users\gp\Documents\Documents\personal\educacion\Discrete Optimization\knapsack>python2 solver.py data/ks_19_0
Traceback (most recent call last):
  File "solver.py", line 60, in <module>
    print solve_it(input_data)
  File "solver.py", line 30, in solve_it
    with open('output.txt') as f:
IOError: [Errno 2] No such file or directory: 'output.txt'

当然!错误发生在Matlab还在打开的过程中。所以它试图访问一个还没有创建的文件。

我该怎么做才能让Python等Matlab完成呢?

非常感谢你的帮助!

相关问题:

2 个回答

7

[为了记录]

正如丹尼尔所指出的,通过在matlab调用中添加几个选项,问题得以解决:

subprocess.call('matlab -nosplash -wait -r "gp(\'tmp.data\')"',shell=0)

之后,它运行得非常顺利。

谢谢

4

你的代码似乎没有考虑到,Matlab 是通过一个启动程序(matlab_root/bin/matlab.exe)和一个主应用程序(matlab_root/bin/xxx/matlab.exe)来运行的。为了让启动程序在主应用程序关闭之前一直保持打开状态,你需要使用 -wait 这个选项。

撰写回答