Python zeromq:TypeError:字符串索引必须是整数,而不是str
我想在机器之间建立发布-订阅通信 我拥有的两台机器是Python zeromq:TypeError:字符串索引必须是整数,而不是str,python,ipc,zeromq,Python,Ipc,Zeromq,我想在机器之间建立发布-订阅通信 我拥有的两台机器是ryu primary和ryu secondary 我在每台机器中遵循的步骤如下 在ryu primary的初始值设定项中(IP地址为192.168.241.131) 来自ryu secondary(IP地址-192.168.241.132) 在初始值设定项中 self.context = zmq.Context() self.sub_socket = self.context.socket(zmq.SUB) se
ryu primary
和ryu secondary
我在每台机器中遵循的步骤如下
在ryu primary的初始值设定项中(IP地址为192.168.241.131)
来自ryu secondary(IP地址-192.168.241.132)
在初始值设定项中
self.context = zmq.Context()
self.sub_socket = self.context.socket(zmq.SUB)
self.pub_socket = self.context.socket(zmq.PUB)
self.pub_port = 5566
self.sub_port = 5566
def establish_zmq_connection(self): # Socket to talk to server
print( "Connection to ryu-secondary..." )
self.sub_socket.connect( "tcp://192.168.241.131:%s" % self.sub_port )
def listen_zmq_connection(self):
print( 'Listen to zmq connection' )
self.pub_socket.bind( "tcp://*:%s" % self.pub_port )
def recieve_messages(self):
while True:
try:
string = self.sub_socket.recv( flags=zmq.NOBLOCK )
print( 'flow mod messages recieved {}'.format(string) )
return string
except zmq.ZMQError:
break
def push_messages(self,msg):
print( 'pushing message to publish socket' )
self.pub_socket.send( "%s" % (msg) )
这些是我拥有的功能
我正在打电话给吕中学:
establish_zmq_connections()
push_messages()
在ryu primary上,当我呼叫
listen_zmq_connection()
recieve_messages()
使用.setsockopt(zmq.SUBSCRIBE='')订阅所有类型的邮件后
但是,我试图发送的消息是以下类型的
msg = {'in_port':in_port,'dst':dst,'actions':actions}
self.push_messages(msg)
但是,在另一方面(receive\u messages()
执行此操作时,我会遇到以下错误
flow_mod = recieve_messages()
flow_mod['in_port']
flow_mod['dst']
flow_mod['actions']
TypeError: string indices must be integers, not str
msg
是一个Python命令,但您正在发送(和接收)格式化为字符串的消息。可能最简单的方法是将msg
序列化为JSON格式,将其作为字符串发送,然后再次将接收到的字符串加载回dict。然后,只有这样,您才能正确访问键和值。类似的方法应该可以工作(请确保在上面的某个位置导入json):
您可以找到json
模块(用于Python 2)和Python 3的完整文档。ZeroMQ API后台
ZeroMQ.send()
.recv()
方法对字符串进行操作。您将一个他们不知道如何处理的dictionary对象传递给他们。将dictionary对象转换为JSON格式,作为针对这种情况的序列化示例,您的工作就完成了
答案=出现类型错误的原因是什么?
如前所述,ZeroMQ的.send()
方法在发送它不理解的对象方面做不了太多,而.recv()部分仍然读取ZeroMQ层上传递的任何内容
因此,您的flow\u mod
变量在函数receive\u messages()
命令中正确地接收字符串作为返回字符串
string=self.sub_socket.recv(flags=zmq.NOBLOCK)
只服务于任何字符串,无论是空字符串还是从套接字的另一侧接收到的任何非零长度字符串
最后:
flow_mod['in_port']
将在语法上崩溃(并且必须这样做),因为变量flow_mod
的内容在此之前分配并进行了类型调整,没有类似字典的访问方法来处理此类语法
因此,这里必须引发类型错误:字符串索引必须是整数,而不是str
异常
Q.E.D.
对象的JSON序列化表示-编码和解码简介:
导入json
>>>打印json.\uu文档__
JSON(JavaScript对象表示法)是
JavaScript语法(ECMA-262第3版)用作轻量级数据
交换格式。
[json]公开了标准库用户熟悉的API
[marshal]和[pickle]模块。它是外部维护的
Python 2.6中包含的[json]库的版本,但
与Python2.4和Python2.5的兼容性以及(目前)已
显著的性能优势,即使不使用可选的C
加速扩展。
对基本Python对象层次结构进行编码::
>>>导入json
>>>dumps(['foo',{'bar':('baz',None,1.0,2)}])
“[“foo”,{“bar”:[“baz”,null,1.0,2]}”
>>>打印json.dumps(“\”foo\bar”)
“\“foo\bar”
>>>打印json.dumps(u'\u1234')
“\u1234”
>>>打印json.dumps(“\\”)
"\\"
>>>打印json.dumps({“c”:0,“b”:0,“a”:0},sort_keys=True)
{a:0,b:0,c:0}
>>>从StringIO导入StringIO
>>>io=StringIO()
>>>json.dump(['streamingapi'],io)
>>>io.getvalue()
“[“流式API”]”
压缩编码::
>>>导入json
>>>dumps([1,2,3,{4':5,'6':7}],sort_keys=True,separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
漂亮的印刷品::
>>>导入json
>>>打印json.dumps({'4':5,'6':7},sort_keys=True,
…缩进=4,分隔符=(',',':'))
{
"4": 5,
"6": 7
}
解码JSON::
>>>导入json
>>>obj=[u'foo',{u'bar':[u'baz',None,1.0,2]}]
>>>loads('[“foo”,{“bar”:[“baz”,null,1.0,2]}]')==obj
真的
>>>加载(“\\”foo\\bar“)==u''foo\x08ar'
真的
>>>从StringIO导入StringIO
>>>io=StringIO(“[“流式API”]”)
>>>json.load(io)[0]=“流式API”
真的
专门化JSON对象解码::
>>>导入json
>>>def as_复合体(dct):
…如果dct中的“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
…返回复数(dct['real',dct['imag'])
…返回dct
...
>>>loads(“{”\uuuuu complex\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
…对象(hook=as_complex)
(1+2j)
>>>从十进制输入十进制
>>>loads('1.1',parse_float=Decimal)==Decimal('1.1'))
真的
专门化JSON对象编码::
>>>导入json
>>>def编码_复合体(obj):
…如果存在(obj,复杂):
…返回[obj.real,obj.imag]
…raise TypeError(repr(o)+“不可JSON序列化”)
...
>>>dumps(2+1j,默认值=encode_complex)
'[2.0, 1.0]'
>>>json.JSONEncoder(默认值=encode_complex).encode(2+1j)
'[2.0, 1.0]'
>>>''.join(json.JSONEncoder(默认值=encode_complex.iterrencode(2+1j))
'[2.0, 1.0]'
@WarrenWeckesser-我想访问该词典中包含的信息,即“in_port”、“dst”和“actions”键的值。谢谢您的回复。您能解释一下如何访问吗
flow_mod = recieve_messages()
flow_mod['in_port']
flow_mod['dst']
flow_mod['actions']
TypeError: string indices must be integers, not str
# on the sending end
msg = {'in_port':in_port,'dst':dst,'actions':actions}
msg_string = json.dumps(msg)
self.push_messages(msg)
# on the receiving end
payload = receive_messages()
message = json.loads(payload)
>>> import json
>>> print json.__doc__
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
[json] exposes an API familiar to users of the standard library
[marshal] and [pickle] modules. It is the externally maintained
version of the [json] library contained in Python 2.6, but maintains
compatibility with Python 2.4 and Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
Encoding basic Python object hierarchies::
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
... indent=4, separators=(',', ': '))
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import json
>>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
Specializing JSON object decoding::
>>> import json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> from decimal import Decimal
>>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
True
Specializing JSON object encoding::
>>> import json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError(repr(o) + " is not JSON serializable")
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'