Python API: how to get the output?

21 ビュー (過去 30 日間)
Balint
Balint 2017 年 2 月 14 日
編集済み: Sebastián Hernández 2017 年 11 月 11 日
I would like to call a long-running matlab function from python and print its output while it is running to see the progress. My problem is that out and err is empty if I run with async=True. Why, and how can I fix it? Here is my python code:
import StringIO
import matlab.engine
import time
out = StringIO.StringIO()
err = StringIO.StringIO()
eng = matlab.engine.start_matlab()
future = eng.long_running(5, stdout=out, stderr=err, async=True)
while not future.done():
time.sleep(2)
print 'output', out.getvalue(), err.getvalue()
print 'result', future.result()
eng.quit()
And the matlab function:
function [ result ] = long_running( secs )
%LONG_RUNNING This function runs for a long time and write to stdout
result = 0;
disp('Long_running function started running...')
for i = 1:secs
fprintf('%d iteration\n',i)
result = result + 1;
pause(1);
end
disp('Long_running function finished running.')
end

採用された回答

Bo Li
Bo Li 2017 年 2 月 14 日
When "async" is set to true, the result along with the output/error are not available until "future.result" is called. How about adding "future.result" after the while loop like this?
while not future.done():
time.sleep(2)
future.result()
print 'output', out.getvalue(), err.getvalue()
print 'result', future.result()
eng.quit()
  2 件のコメント
Balint
Balint 2017 年 2 月 14 日
If there is no way to access the output/error stream while the function is running, than the non-async version can do the job for me. Thanks for the answer!
Sebastián Hernández
Sebastián Hernández 2017 年 11 月 11 日
編集済み: Sebastián Hernández 2017 年 11 月 11 日
I need something like this:
...
std_in = StringIO.StringIO()
future = eng.long_running(5, stdout=out, stderr=err, stdin=std_in, async=True)
std_in.write(12)
...
but stdin is not a valid argument. Do you know any way to achieve this? I will run an script that has
a=input('some input')
and I need to pass the input from python.
Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall MATLAB from Python についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by