2

Is there a way to run a Matlab.m file from Python 2.7 Shell or a .py code? I tried using the following code:

import os   
os.chdir(r'D:\The_folder_where_the_file_is')                             
os.startfile("The_desired_Matlab_file.m")

but then , it just opens the .m file, without running it ( as if when you press F5 in Editor Matlab).What shall i do ?
(I've already downloaded pymat and win32, if that helps)

sachleen
  • 30,730
  • 8
  • 78
  • 73
p_a321
  • 119
  • 1
  • 2
  • 7
  • An example to run MATLAB with the -r option from Python can be found [here](http://stackoverflow.com/questions/20769415/how-do-i-import-a-data-file-as-a-matrix-and-run-a-m-file-from-a-python-script/20770976#20770976) – BHF Jan 12 '14 at 14:04

2 Answers2

2

Python can't run .m files directly, you need to use matlab or octave. Python can run external commands with the subprocess.Popen() function. Try something like this:

import subprocess, os
os.chdir(r'D:\The_folder_where_the_file_is')
subprocess.Popen(['matlab','The_desired_Matlab_file.m'])

You mentioned you have pymat installed and want to use that. In that case, the correct way to open a .m file is to first use the pymat.open() function to start a session, then to run any commands with the pymat.eval() function. See the documentation here for an example and more details.

Dan
  • 12,157
  • 12
  • 50
  • 84
  • Actually, I'm sorry, i wanted to say Numpy instead of pymat . I tried to install pymat, but it seems to not run in version beyond python 2.2 and right now i am using 2.7 . Thank you very much for your help, i'll look in subprocess library for the proper function – p_a321 Jan 12 '14 at 00:12
  • Subprocess is part of the standard library. You don't have to separately install anything. – Dan Jan 12 '14 at 00:16
0

Recently, I have encounted the same problem, finally I crack it under this way. I work on Windows 7 64bit

First, You need put your 'matlab.exe' into your system path 'Path'

Second, try this code

    import os, subprocess
    os.chdir(r'D:\the-fold-where-your-m-file-is')
    print os.listdir(os.curdir)
    returnCode = subprocess.call("matlab -r your-m-file-name.m")
    print "Return Code: ", returnCode

Hope this answer will help others, thank you !