如何在Processing草图与Python程序之间通信?
我有一个用Processing写的程序,用来处理实时音频,还有一个用Python写的程序,用来通过蓝牙低能耗和外部设备进行通信。请问有没有简单的方法可以把Processing中的数值发送到Python?我是不是应该建立一个串口连接,通过这种方式传递字节数据?
1 个回答
12
考虑到它们是在同一台电脑上运行,最好的办法是用套接字(sockets)在Python这边创建一个服务器,然后在Processing这边创建一个客户端,通过这种方式把数据从客户端发送到服务器。Python服务器会一直等待Processing客户端的连接,一旦收到数据就会进行处理。
网上有很多相关的例子,不过这里有Processing和Python文档中给出的例子(Processing示例中的端口号从5204
改成了50007
,这样你可以直接复制粘贴):
import processing.net.*;
Client myClient;
void setup() {
size(200, 200);
/* Connect to the local machine at port 50007
* (or whichever port you choose to run the
* server on).
* This example will not run if you haven't
* previously started a server on this port.
*/
myClient = new Client(this, "127.0.0.1", 50007);
}
void draw() {
myClient.write("Paging Python!"); // send whatever you need to send here
}
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
print(data) # Paging Python!
# do whatever you need to do with the data
conn.close()
# optionally put a loop here so that you start
# listening again after the connection closes