【问题标题】:Run a MATLAB file from Python 2.7 Shell从 Python 2.7 Shell 运行 MATLAB 文件
【发布时间】:2015-05-14 21:51:29
【问题描述】:

有没有办法从 Python 2.7 Shell 或 .py 代码运行 Matlab.m 文件?我尝试使用以下代码:

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

但是,它只是打开 .m 文件,而不运行它(就像您在编辑器 Matlab 中按 F5 时一样)。我该怎么办?
(我已经下载了 pymat 和 win32,如果有帮助的话)

【问题讨论】:

  • 在 Python 中使用 -r 选项运行 MATLAB 的示例可以在 here 中找到

标签: python matlab


【解决方案1】:

Python不能直接运行.m文件,需要使用matlab或者octave。 Python 可以使用subprocess.Popen() 函数运行外部命令。试试这样的:

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

您提到您已安装 pymat 并希望使用它。在这种情况下,打开.m 文件的正确方法是首先使用pymat.open() 函数启动会话,然后使用pymat.eval() 函数运行任何命令。有关示例和更多详细信息,请参阅文档 here

【讨论】:

  • 其实,对不起,我想说 Numpy 而不是 pymat 。我尝试安装 pymat,但它似乎无法在 python 2.2 之后的版本中运行,现在我正在使用 2.7 。非常感谢您的帮助,我会在子进程库中查找正确的功能
  • 子进程是标准库的一部分。您不必单独安装任何东西。
【解决方案2】:

最近也遇到了同样的问题,终于用这种方式破解了。 我在 Windows 7 64 位上工作

首先,您需要将“matlab.exe”放入系统路径“Path”

其次,试试这段代码

    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

希望这个答案对其他人有所帮助,谢谢!

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2014-01-21
    相关资源
    最近更新 更多