Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

matlab - Python subprocess.call doesn't wait for command to execute

I'm new to python, which I need to use for an assignment in a course. I developed the solution (an optimization algorithm) in Freemat / octave / matlab .m file and wanted to call it from Python (the python code will be called by a grading python script).

The .m file reads a file called tmp.data and writes the output to output.txt. The python script should then read from that output and convert it to the result that the grading script expects.

All runs fine, except I haven't been able to make Python wait for the call to Matlab to complete and therefore generates an error on the following lines.

Here's the code:

#!/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) + '
'
    # 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)'

As you see, I've tried with subprocess.call, popen, os.system... to no avail. All of them give me similar errors:

C:UsersgpDocumentsDocumentspersonaleducacionDiscrete Optimizationknapsack>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'

Of course! The error comes while matlab is still in the process of opening. It thus is trying to access a file that hasn't been created yet.

What should I do to get Python to wait for Matlab to complete??

I appreciate your kind help, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[for the record]

As Daniel pointed out, it was solved by introducing a couple options into the matlab call:

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

After that, it ran beautifully.

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...