Return print statement output from Python file in real time when using pyrunfile

조회 수: 19 (최근 30일)
I have a Python file I am calling using pyrunfile in Matlab R2022b on Windows as follows:
pyrunfile("filetocall.py 'inputvar1' 'inputvar2'")
Sometimes this filetocall.py can take a while to run, and it would be nice to see the print statements in my Python code that provide updates on its progress as it's running. What it currently does is show all the print statements in one block of text after the file finishes running. From what I understand this has to do with the output generated by Python print statements being buffered and it doesn't flush the output until the Python function returns.
I've tried flushing the output buffer manually in my Python code by:
  1. Using sys.stdout.flush() after a print statement in my Python code
  2. Setting the print function's flush argument to True, ie. print('Some statement', flush=True)
but unfortunately neither worked. Is there currently no way to flush output from a Python file on the Matlab side in 'real time'? If not, it's not the end of the world, would just be handy.

채택된 답변

VINAYAK LUHA
VINAYAK LUHA 2023년 9월 20일
Hi Spencer.
It is my understanding that you are executing a python script from MATLAB using the pyrunfilecommand and wish to flush the print output from python output buffer to MATLAB command window in real-time.
Here are few workarounds to address the issue
  • Use the python “loggingmodule instead of print statements as the former provides more flexibility and control over the output and buffering behaviour and invoke the script execution directly by the OS using the system command in MATLAB as shown below. .py file
.m file
  • Execute the python script using “pyrunfile function” in a live “.mlx file.
  • Modify the python script to write the buffer content to a shared .txt file from which MATLAB can also read the content.
  • Leverage IPC constructs like message queues or socket connections to send data from python script to MATLAB.
Explore the following documentations for details-
Regards,
Vinayak Luha

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by