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!

laike9m
  • 18,344
  • 20
  • 107
  • 140

2 Answers2

4

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'])
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thx,it works!Another question,is there a way that I can "reuse" matlab instead of starting it again and again? – laike9m Apr 26 '13 at 11:25
  • 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. – David Heffernan Apr 26 '13 at 11:32
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.

JonB
  • 350
  • 1
  • 7
  • thank you!I need "wait" cause the ML output is what I'll deal with next. – laike9m Apr 26 '13 at 11:27
  • It seems that PyMat and mlabwrap haven't updated for years...But I'm using python3... – laike9m Apr 26 '13 at 12:57
  • 2
    @laike9m: use the COM interface: http://stackoverflow.com/a/2885122/97160 (make sure you have run `matlab -regserver` at least once before) – Amro Apr 26 '13 at 13:41
  • @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 – Amro Apr 26 '13 at 14:24