Run MATLAB executable from Python
조회 수: 55 (최근 30일)
이전 댓글 표시
Hi All,
This is a follow up to my previous question posted here, https://in.mathworks.com/matlabcentral/answers/1882532-run-matlab-executable-from-python?s_tid=srchtitle
I am trying to run a MATLAB executable (main.exe) from Python. main.exe file was generated using the .m files in my project, using the application compiler.
To run the executable from Python, I tried
import subprocess
cmd = r"C:/Windows/System32/cmd I:/sim/main/main.exe"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000)
process.wait()
But this doesn't generate the output file.
In MATLAB's command prompt, when I run the executable (!main) output is saved in the results folder in 50 secs.
But the output file isn't generated while running from Python.
Suggestions on how to run the executable in Python will be really helpful.
댓글 수: 3
Roshan Swain
2022년 12월 26일
편집: Roshan Swain
2022년 12월 26일
Hi,
As mentioned in the python documentation using wait() with stdout=PIPE can cause deadlock. Refer here: https://docs.python.org/2/library/subprocess.html#subprocess.Popen:~:text=Warning%20This%20will%20deadlock%20when%20using%20stdout%3DPIPE%20and/or%20stderr%3DPIPE%20and%20the%20child%20process%20generates%20enough%20output%20to%20a%20pipe%20such%20that%20it%20blocks%20waiting%20for%20the%20OS%20pipe%20buffer%20to%20accept%20more%20data.%20Use%20communicate()%20to%20avoid%20that.
Try using the communicate() method instead of wait(), like this:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000).communicate()
Also much better if you place the executable file in the same location as python file for testing( can avoid any path issues for now),
Let me know if this resolves the issue, then I will create an answer for this one.
답변 (1개)
Ishaan
2025년 1월 22일 11:49
As mentioned by @Roshan Swain’s comment, it is mentioned in the documentation that using “stdout=subprocess.PIPE” with “process.wait()” will result in a deadlock condition.
You can use the “capture_output” argument to get the output from the exe you are executing.
Here is a sample code, that I tested works.
>> import subprocess
>> exe_path = r"I:/sim/main/main.exe"
>> process = subprocess.run(exe_path, capture_output=True, text=True)
Post this, you can access the output through “process.stdout” and “process.stderr” respectively.
Lastly, this works for any executable in general, not just to the ones generated from MATLAB.
Hope this helps.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!