从外部控制 python 线程 [英] Control a python thread from outside

查看:27
本文介绍了从外部控制 python 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它需要在后台持续运行,但能够接收指令进行更改.我正在运行这个线程,它将数据发送到 Arduino 并接收回数据:

I have a program, which needs to continuously run in the background, but be able to receive instructions to change. I have this thread running, which sends data to an Arduino and receives data back:

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,但似乎无法在服务器上运行线程,然后通过客户端控制它.

Now I need to change the command I send with an external program.
I tried using Pyro4, but I can not seem to get a Thread running on the server and then controlling it with the client.

有什么想法吗?

推荐答案

Scott Mermelstein 的建议很好,我希望你能研究进程间通信.但作为让您入门的快速示例,我建议您像这样修改代码:

Scott Mermelstein's advice is good, I hope you will look into interprocess communications. But as a quick example to get you started, I would suggest modifying your code like this:

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) 从线程外部向队列添加命令.

This code uses a threading.Event as a signal to the thread that it should stop. It then uses a queue.Queue as a way to send commands to the thread from outside. You will need to use q.put(command) to add commands to the queue from outside the thread.

我没有用 Arduino 测试这个,我创建了自己的 send 版本用于测试刚刚返回的命令.

I didn't test this with an Arduino, I created my own version of send for testing that just returned the command.

这篇关于从外部控制 python 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆