首页 > 解决方案 > 如何将“字节字符串”输入参数传递给从 MATLAB 调用的 python 函数?

问题描述

我正在尝试从 MATLAB 调用 Python 函数。在此 Python 函数中,输入参数的类型为“字节字符串”。我无法将“字节字符串”参数传递给 Python

我正在尝试使用 ipc 创建服务器-客户端应用程序,其中服务器是纯 Python 应用程序,客户端是调用 python 函数的 MATLAB 应用程序。我在 Python 3.7 环境中安装了 Anaconda。

Python 服务器代码:

from multiprocessing.connection import Listener

address = ('localhost', 6000)     # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
conn = listener.accept()
print('connection accepted from', listener.last_accepted)
while True:
    msg = conn.recv()
    print(msg)
    if msg == 'close':
        conn.close()
        break
listener.close()

Python 客户端代码(用于测试目的):

from multiprocessing.connection import Client

address = ('localhost', 6000)
conn = Client(address, authkey=b'secret password')
conn.send('close')
can also send arbitrary objects:
conn.send(['a', 2.5, None, int, sum])
conn.close()

在 Python 中执行时,上述服务器-客户端对工作正常。

现在在命令行中尝试 MATLAB 等效于上述 Python 客户端代码:

>> mp_pyModule = py.importlib.import_module('multiprocessing.connection');
>> client_fn = mp_pyModule.Client;
>> address = py.tuple({'localhost',int16(6000)});
>> conn = client_fn(address,pyargs('authkey','secret password'));
Error using connection>Client (line 495)
Python Error: TypeError: authkey should be a byte string

我知道我在上面传递了一个正常的字符串,这就是出错的原因。我要求将上述参数“秘密密码”作为“字节字符串”发送。怎么可能做到?

Python 不支持的类型(https://in.mathworks.com/help/matlab/matlab_external/unsupported-matlab-types.html)没有提及任何关于此的内容。还有其他限制吗?如果我转向 Python 2,这可能会奏效。

标签: pythonmatlab

解决方案


找到的解决方案:使用py.bytes(uint8(string))

例如: conn = client_fn(address,pyargs('authkey',py.bytes(uint8('secret password'))));

学分 - Walter Roberson@Mathworks


推荐阅读