3

Here is my python code

DosCmd = 'matlab -wait -automation -nosplash -r "run \'' + to_run + "'\""
os.system(DosCmd)
curve_file = open('curve/'+str(index)+'.curve','r') 

I run a .m file in a python script,it works fine but after executing the .m file,it is stuck in os.system(DosCmd). To make python run the following code,I have to close this window:

enter image description here

Since this part of code is in a loop,it really disturbs me. I found someone on the Internet says that matlab can exits automatically after executing the .m file,but mine just doesn't.Will someone tell what I did wrong or what should I do?Thx!

2
  • Try the break keys CTRL+C Commented Apr 26, 2013 at 10:51
  • 1
    Have you tried exit? Commented Apr 26, 2013 at 10:53

2 Answers 2

5

Add a call to exit to the MATLAB code that you execute.

DosCmd = 'matlab -wait -automation -nosplash -r "run \'' + to_run + "', exit\""

Your quoting looks a little wonky mind you, but you just need to add , exit to the end of the command that you pass in the -r argument.

By the way, this would be a lot easier with subprocess so that you could let subprocess do the quoting for you.

subprocess.check_call(['matlab', '-wait', '-automation', '-nosplash', 
    '-r', 'run \' + to_run + \', exit'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thx,it works!Another question,is there a way that I can "reuse" matlab instead of starting it again and again?
Well, JonB covered that rather well I think. mlabwrap looks good to me. You could use MATLAB as a COM server, but I suspect mlabwrap will be much cleaner.
2

Add the command exit to the last line of your script.
The -wait commandline switch means the starter application won't close until matlab exits. If you are acutally having python do something with the ML output, then -wait is correct, otherwise get rid of the -wait.

Also, are you sure you really want to be launching new matlab session each time in a loop? Matlab exposes DDE functionality, which would allow you to open one instance and send commands.

Or, you might look at PyMat, or mlabwrap, etc, one of the existing python to matlab bridge libraries.

4 Comments

thank you!I need "wait" cause the ML output is what I'll deal with next.
It seems that PyMat and mlabwrap haven't updated for years...But I'm using python3...
@laike9m: use the COM interface: stackoverflow.com/a/2885122/97160 (make sure you have run matlab -regserver at least once before)
@laike9m: just run matlab.exe -regserver from the console outside MATLAB. It registers MATLAB as a COM server. You only need to do this once if you havent already

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.