【问题标题】:Sending multiple values via sockets with Python to Pure Data使用 Python 通过套接字将多个值发送到 Pure Data
【发布时间】:2016-06-18 16:51:44
【问题描述】:

我正在使用此代码向 Pure Data 发送信息,在 Python 控制台中我看到了两个不同的变量,但是 Pure Data 不断接收它们,而不是作为两个单独的数字相加。

import bge

# run main program
main()

import socket

# get controller 
cont2 = bge.logic.getCurrentController()
# get object that controller is attached to 
owner2 = cont2.owner
# get the current scene 
scene = bge.logic.getCurrentScene()
# get a list of the objects in the scene 
objList = scene.objects

# get object named Box 
enemy = objList["enemy"]
enemy2 = objList["enemy2"]

# get the distance between them 
distance = owner2.getDistanceTo(enemy)
XValue = distance  
print (distance)
# get the distance between them 
distance2 = owner2.getDistanceTo(enemy2)
XValue = distance2  
print (distance2)    

tsr = str(distance + distance2)     
tsr += ';'
host = '127.0.0.1'
port = 50007
msg = '123456;'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(tsr.encode())
s.shutdown(0)
s.close()

我需要发送最多 10 个不同距离的物体,这与寻找与敌人的距离有关

【问题讨论】:

  • 请尝试将您的问题简化为最小示例。例如查询bge 以获取enemies 是相当无关紧要的,msgXValue 分配是做什么的?
  • 这能回答你的问题吗? How to concatenate two integers in Python?

标签: python sockets puredata


【解决方案1】:

问题完全出在你的 python 代码中:

您有两个变量distance1distance2(假设distance1=666distance2=42 然后构造一个字符串:

tsr = str(distance1 + distance2)

现在这将首先评估表达式distance1+distance2(将它们相加为708),然后根据该值创建一个字符串("708")。 因此,您的 Python 脚本会发送经过处理的数据。

所以你的第一步是在“添加”它们之前将你的值转换为 strings(因为 adding 字符串实际上是 appending 它们):

tsr = str(distance1) + str(distance2)

但这真的会给你一个字符串"66642",因为你没有告诉appender用空格分隔to值。

所以一个正确的解决方案是:

tsr = str(distance1) + " " + str(distance2)
tsr += ";"

【讨论】:

    【解决方案2】:
    var1="5Hello3How3Are3you8I'm FINE2is4that3so?3yes"
    #initial measurement
    
    m=var1[0]
    m=int(m)
    print var1[1:1+m]
    INIT_LEN=1
    LENGTH=m
    n=1
    NUMBER_FRAMES=9-1 #number of bytes 9
    
    while n<=NUMBER_FRAMES:
      INIT_LEN=INIT_LEN+LENGTH
      l=var1[INIT_LEN]
      INIT_LEN=INIT_LEN+1
      LENGTH=int(l)
      print var1[INIT_LEN:INIT_LEN+LENGTH]
      n=n+1
    

    如果您愿意将多个连接的字符串作为单个连接字符串传输,我建议您查看当前代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-01
      • 2013-05-23
      • 2021-06-15
      • 2012-08-09
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多