Run MATLAB executable from Python

24 vues (au cours des 30 derniers jours)
Deepa Maheshvare M.
Deepa Maheshvare M. le 23 Déc 2022
Réponse apportée : Ishaan le 22 Jan 2025
Hi All,
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 commentaires
Torsten
Torsten le 24 Déc 2022
Roshan Swain
Roshan Swain le 26 Déc 2022
Modifié(e) : Roshan Swain le 26 Déc 2022
Hi,
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.

Connectez-vous pour commenter.

Réponses (1)

Ishaan
Ishaan le 22 Jan 2025
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.

Catégories

En savoir plus sur Python Package Integration dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by