2

我想从 Python 访问 Matlab(在 Windows 上,远程和通过 COM 接口)。我的目标是:Matlab 正在做一些工作并永久更改某个变量的值。我需要知道该值何时超过某个常数。现在,我正在无限循环中轮询 Matlab 中该变量的值,该循环会在超过该值时中断。但是,我想让 Matlab 做这项工作并告诉什么时候会出现这种情况,而我却懒洋洋地坐在那里听。有没有办法做到这一点,如何做到最好?我曾想过定义一个要传递给 Matlab 的回调函数,它在超出事件时会触发 Python 中非忙等待循环的中断,但我怀疑它会起作用。我在 Matlab 和 Python 方面都不是很有经验,因此非常感谢提示。

涉及很多其他代码,但基本上现在它就像

connectToMatlab(*args)
while True:
    val = getValueFromMatlab()
    if val > constant or timeout: break

我的想法是

def breakLoop():
    ...  

connectToMatlab(breakLoop, *args)
while True:
    time.sleep(1) # or some alternate non-busy-wait

然后让 Matlab调用breakLoop(). val > constant但是,我不知道是否可以让 Matlab 通过回调来做到这一点,如果可以,如何实现这样的breakLoop()-Function。

4

1 回答 1

2

你可以用另一种方式来解决这个问题,并使用文件系统作为在 MATLAB 和 Python 之间传递消息的一种方式。

在您的 MATLAB 代码中,每次更改变量时,检查它是否超过某个阈值。如果是,请在预定位置创建一个新文件。将此视为触发事件。

现在在你的 python 代码中,使用一些可用的方法来监听文件系统中的变化,并通过指示一些变量来中断循环来响应。


编辑

这是提出的解决方案的框架:

matlab_script.m

%# directory that Python code is watching for modifications
dirPath = 'some_directory';

x = 0;
for i=1:1000
    %# some lengthy operation
    pause(0.5)
    x = x + 1;

    %# check if variable exceeds threshold
    if x > 10
        %# save the workspace to MAT-file inside the directory watched.
        %# this shall trigger the notification in Python
        save( fullfile(dirPath,'out.mat') )
        break
    end
end

python_code.py

import os, sys, time
import win32file, win32event, win32con

# stub your functions in my case
def connectToMatlab():
  pass
def getValueFromMatlab():
  return 99

# path to predetermined directory to watch
dirPath = "some_directory"
dirPath = os.path.abspath(dirPath)

# start/connect to a MATLAB session, running the script above
connectToMatlab()

# set up folder watching (notify on file addition/deletion/renaming)
print "Started watching '%s' at %s" % (dirPath, time.asctime())
change_handle = win32file.FindFirstChangeNotification(
  dirPath, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME)

# time-out in 10 sec (win32event.INFINITE to wait indefinitely)
timeout = 10000

try:
  # block/wait for notification
  result = win32event.WaitForSingleObject(change_handle, timeout)

  # returned because of a change notification
  if result == win32con.WAIT_OBJECT_0:
    # retrieve final result from MATLAB
    print "MALTAB variable has exceeded threshold at %s" % time.asctime()
    val = getValueFromMatlab()

  # timed out
  elif result == win32con.WAIT_TIMEOUT:
    print "timed-out after %s msec at %s" % (timeout,time.asctime())
    val = None    # maybe to indicate failure

finally:
  # cleanup properly
  win32file.FindCloseChangeNotification(change_handle)

# work with val
print val

WaitForSingleObject函数首先检查指定对象的状态。如果它是无信号的,则调用线程进入有效的等待状态,并在等待对象发出信号(或超时间隔过去)时消耗非常少的处理器时间。

您会看到,当线程引用处于非信号状态的对象时,会立即进行上下文切换,即从处理器中取出它并进入等待/睡眠模式。稍后当对象发出信号时,线程被放回可运行队列并准备好执行。

在这种等待中,虽然在上下文切换中存在一些开销,但在等待状态下不会浪费 CPU 周期。

将此与“轮询并等待”方法进行比较,其中线程在某种循环中等待并检查感兴趣对象的状态。这被称为自旋或忙等待,这可以证明是对 CPU 周期的浪费。

现在感谢 pywin32 模块,我们可以直接使用这些WaitFor...功能。该实现应该是MSDN 中给出的标准示例的直接移植。

或者,您可以使用 PyQt 库及其QFileSystemWatcher类,而不是直接使用 Win32 API。

于 2012-06-09T20:03:25.060 回答