python - 如何将“字节字符串”输入参数传递给从 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,这可能会奏效。
解决方案
找到的解决方案:使用py.bytes(uint8(string))
例如:
conn = client_fn(address,pyargs('authkey',py.bytes(uint8('secret password'))));
学分 - Walter Roberson@Mathworks
推荐阅读
- php - 不知道为什么 'relation' => 'AND' 在这段代码中不起作用?
- javascript - 从聊天框中隐藏 div
- vert.x - Vertx EventBus 被阻塞
- webgl - WebGL 中的统一缓冲区?
- c# - 无法在 .NET Core 中设置私钥
- html - 位置粘性不起作用(Element.io 和 VueJS)
- java - NullpointerException 模拟测试
- google-oauth - Google OAuth2 SignIn 方法在页面加载时触发
- javascript - 将按钮单击的值存储在变量中,以便可以存储在Sharepoint列表中
- jquery - 如何从一个特定的类中选择元素?