Skip to main content
 首页 » 编程设计

分配后Python对象类型发生了变化,这是一个错误吗

2025年05月04日13jirigala

boy变量的内容字符串是从AMQP收到的消息队列。它是一个 json 字符串。会被标准的json库转为python对象

body         = {"TestPlanName": "DemoPlan", "ReplyTo": "Reply", "Drivers": [1, 2, 3], "Cmd": "Start", "IsResetTool": true, "TestCycleId": 1} 
logging.debug('Received message body: %s' % body) 
msg          = json.loads(body) 
for key, value in msg.items(): 
    logging.debug('key %s, type %s, value %s' % (key, type(value), value)) 
    logging.debug('key %s, type %s, value %s' % (key, type(value), msg[key])) 
 
logging.debug('Parsed json object %s' % msg) 
 
cmd          = msg[EXECUTOR.CMD], 
drivers      = msg[EXECUTOR.DRIVERS],  
testCycleId  = msg[EXECUTOR.TEST_CYCLE_ID],  
testPlanName = msg[EXECUTOR.TEST_PLAN_NAME] 
replyTo      = msg[EXECUTOR.REPLY_TO] 
 
logging.debug('Parsed result type %s value %s' % (type(cmd          ), cmd          )) 
logging.debug('Parsed result type %s value %s' % (type(drivers      ), drivers      )) 
logging.debug('Parsed result type %s value %s' % (type(testCycleId  ), testCycleId  )) 
logging.debug('Parsed result type %s value %s' % (type(dmType       ), dmType       )) 

输出日志文件:

DEBUG msg:Received message body: {"TestPlanName": "DemoPlan", "ReplyTo": "Reply", "Drivers": [1, 2, 3], "Cmd": "Start", "DMType": "DM2", "IsResetTool": true, "TestCycleId": 1} 
DEBUG msg:key TestPlanName, type <type 'unicode'>, value DemoPlan 
DEBUG msg:key TestPlanName, type <type 'unicode'>, value DemoPlan 
DEBUG msg:key ReplyTo, type <type 'unicode'>, value Reply 
DEBUG msg:key ReplyTo, type <type 'unicode'>, value Reply 
DEBUG msg:key Drivers, type <type 'list'>, value [1, 2, 3] 
DEBUG msg:key Drivers, type <type 'list'>, value [1, 2, 3] 
DEBUG msg:key Cmd, type <type 'unicode'>, value Start 
DEBUG msg:key Cmd, type <type 'unicode'>, value Start 
DEBUG msg:key IsResetTool, type <type 'bool'>, value True 
DEBUG msg:key IsResetTool, type <type 'bool'>, value True 
DEBUG msg:key TestCycleId, type <type 'int'>, value 1 
DEBUG msg:key TestCycleId, type <type 'int'>, value 1 
DEBUG msg:Parsed json object {u'TestPlanName': u'DemoPlan', u'ReplyTo': u'Reply', u'Drivers': [1, 2, 3], u'Cmd': u'Start', u'DMType': u'DM2', u'IsResetTool': True, u'TestCycleId': 1} 
DEBUG msg:Before call ScriptDispatcher.ScriptDispatcher_CleanStopedExecutors args: () kwargs:{}      
DEBUG msg:After call ScriptDispatcher.ScriptDispatcher_CleanStopedExecutors  return: None 
DEBUG msg:Parsed result type <type 'tuple'> value (u'Start',) 
DEBUG msg:Parsed result type <type 'tuple'> value ([1, 2, 3],) 
DEBUG msg:Parsed result type <type 'tuple'> value (1,) 
DEBUG msg:Parsed result type <type 'unicode'> value DM2 
DEBUG msg:Parsed result type <type 'unicode'> value DemoPlan 
DEBUG msg:Parsed result type <type 'unicode'> value Reply 

msg字典的item赋值后,unicode字符串类型u'Start'变为元组,列表[1,2,3]为更改为 ([1,2,3],) 并且数字 1 更改为 (1,)!

请您参考如下方法:

你的作业中有尾随逗号,即 cmd = msg[EXECUTOR.CMD], <-- 那个尾随逗号将使它成为一个元组,删除那些,它会按照你的预期行事。