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)

1
  • An example to run MATLAB with the -r option from Python can be found here Commented Jan 12, 2014 at 14:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
Subprocess is part of the standard library. You don't have to separately install anything.
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 !

Comments

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.