Problem with using system call to execute python script from MATLAB
I have a MATLAB function that needs to communicate (not rapidly, and not often) with python code. I have MATLAB write numbers to a file. Python reads the file, does some calculations, and writes some results to another file. MATLAB then reads that file and continues on its way.
The problem I am having is when I want to execute the python script from MATLAB. I have found in the past that simply performing a system call within MATLAB has been sufficient:
system('python myscript.py')
However, it seems to not like the numpy function 'loadtxt' when it reaches that point in the python script:
NameError: name 'loadtxt' is not defined
I am defining it (from numpy import *). If I just execute the script from terminal, it reads in the file using loadtxt just fine. It is only when I execute the script using the system call do I get that error. The python .py file is开发者_运维技巧 in the same directory as the MATLAB .m file that is making the system call. I have executed other scripts without loadtxt just fine using this same method.
Any suggestions?
It looks like you're using OS X. It is highly advisable not to attempt to screw around with the global definition of what python interpreter to use in OS X.
You can probably just call the desired interpreter directly. So instead of calling system('python myscript.py')
, get the desired interpreter's full path into a variable and call:
system([use_this_python ' myscript.py'])
or something similar.
Exactly how you want to determine what python interpreter to use is between you and whoever is using this. Perhaps have it just call "python" by default, but allow the user to specify some arbitrary interpreter via config file.
The shell on your system and the shell opened by Matlab when you execute the system
command are not necessarily the same.
Importantly, there could be different environment variables. Try e.g. executing system('echo $PATH')
to check whether you have access to all your libraries.
精彩评论