我有一个程序,需要在后台连续运行,但能够接收更改说明。我运行了这个线程,它将数据发送到Arduino并接收数据:
class receiveTemp (threading.Thread):
def __init__(self, out):
threading.Thread.__init__(self)
self.out = out
def run(self):
self.alive = True
try:
while self.alive:
rec = send("command")
self.out.write(rec)
except BaseException as Error:
print(Error)
pass
现在我需要用外部程序更改我发送的命令 我尝试使用Pyro4,但我似乎无法在服务器上运行Thread,然后通过客户端控制它。
有什么想法吗?
答案 0 :(得分:1)
Scott Mermelstein的建议很好,我希望你会研究进程间通信。但作为一个让你入门的简单例子,我建议修改你的代码:
import threading
import queue
import sys
import time
class receiveTemp (threading.Thread):
def __init__(self, out, stop, q):
threading.Thread.__init__(self)
self.out = out
self.q = q
self.stop = stop
def run(self):
while not self.stop.is_set():
try:
cmd = self.q.get(timeout=1)
except queue.Empty:
continue
try:
rec = send(cmd)
self.out.write(rec)
except BaseException as Error:
print(Error)
pass
stop = threading.Event()
q = queue.Queue()
rt = receiveTemp(sys.stdout, stop, q)
rt.start()
# Everything below here is an example of how this could be used.
# Replace with your own code.
time.sleep(1)
# Send commands using put.
q.put('command0')
q.put('command1')
q.put('command2')
time.sleep(3)
q.put('command3')
time.sleep(2)
q.put('command4')
time.sleep(1)
# Tell the thread to stop by asserting the event.
stop.set()
rt.join()
print('Done')
此代码使用threading.Event
作为应该停止的线程的信号。然后使用queue.Queue
作为从外部向线程发送命令的方法。您需要使用q.put(command)
从线程外部向队列添加命令。
我没有使用Arduino进行测试,我创建了自己的send
版本进行测试,只是返回了命令。