相关疑难解决方法(0)

守护程序线程说明

Python文档中 它说:

线程可以标记为"守护程序线程".这个标志的意义在于,当只剩下守护进程线程时,整个Python程序都会退出.初始值继承自创建线程.

有没有人更明确地解释这意味着什么或一个实际的例子显示你想要将线程设置为何处daemonic


为我澄清一下:

因此,如果您希望它们在主线程退出后继续运行,那么您唯一不会将线程设置为守护程序的时间是?

python multithreading daemon python-multithreading

227
推荐指数
8
解决办法
12万
查看次数

如何让Python线程优雅地完成

我正在做一个涉及数据收集和日志记录的项目.我有两个运行的线程,一个集合线程和一个日志记录线程,都在main中启动.我正在尝试使用Ctrl-C允许程序正常终止.

我正在使用a threading.Event向线程发出信号以结束它们各自的循环.它可以正常停止该sim_collectData方法,但它似乎没有正确停止该logData线程.该Collection terminated打印语句永远不会执行,程序公正摊位.(它没有结束,只是坐在那里).

第二个while循环logData是确保记录队列中的所有内容.目标是让Ctrl-C立即停止收集线程,然后允许日志记录线程完成清空队列,然后才完全终止程序.(现在,数据刚刚被打印出来 - 最终它将被记录到数据库中).

我不明白为什么第二个线程永远不会终止.我基于我在这个答案上所做的事情:在一段时间后停止一个线程.我错过了什么?

def sim_collectData(input_queue, stop_event):
    ''' this provides some output simulating the serial
    data from the data logging hardware. 
    '''
    n = 0
    while not stop_event.is_set():
        input_queue.put("DATA: <here are some random data> " + str(n))
        stop_event.wait(random.randint(0,5))
        n += 1
    print "Terminating data collection..."
    return

def logData(input_queue, stop_event):
    n = 0

    # we *don't* want to loop based on queue size because …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-2.7

6
推荐指数
1
解决办法
8864
查看次数

退出导入的模块而不退出主程序 - Python

我有一个名为的模块randomstuff,我将其导入到我的主程序中。问题是,有时需要停止正在运行的代码randomstuff,而不影响主程序。

我尝试过 exit()、quit() 和一些操作系统函数,但它们都想关闭我的主程序。在模块内部,我有一个线程来检查模块是否应该停止 - 那么当它意识到必须停止程序时,我应该在线程中放置什么函数。

关于如何解决这个问题有什么想法吗?谢谢

python exit quit

6
推荐指数
1
解决办法
3490
查看次数

如何在一段时间内(例如从上午 10 点到下午 12:30)启动/停止 Python 函数?

我正在尝试创建一个函数(例如def startTime()),该函数执行另一个函数def runFunc(),该函数每天在上午 10 点使用 python 脚本开始执行,并在下午 12:30 自动停止(或脚本结束)。

例子: startTime(start_time, stop_time,runFunc)

任何人都可以帮助我吗?

我试图安排startTime从上午 10 点到下午 12:30。

import threading
import schedule
import time

def runFunc(interval, innerFunc, iterations = 0):
   if iterations != 1:
      threading.Timer (interval,runFunc, [interval, innerFunc , 0 ]).start ()
   innerFunc ()

def A():
     print "Hello World- A"
def B():
     print "Hello World- B"
Run Code Online (Sandbox Code Playgroud)

我试过这个但没有用:

def startTime(job):
      schedule.every().day.at("10:00").do(job)
      while True:
           schedule.run_pending()

startTime(runFunc(60,A))
startTime(runFunc(300,B))
Run Code Online (Sandbox Code Playgroud)

runFunc(60,A) 运行良好,但无法在上午 10 点到下午 12:30 之间安排 runFunc。

其它的办法

from …
Run Code Online (Sandbox Code Playgroud)

python datetime schedule

5
推荐指数
1
解决办法
5557
查看次数

如何使用 Python 3 停止线程内的 youtube-dl 下载

我有一个从特定 URL 下载视频的函数,我通过线程启动此函数以避免 GUI 冻结,但我想要一个函数来停止或暂停下载。这个怎么做?这是代码:

def download_videos(self):
     ydl1 = youtube_dl.YoutubeDL(self.get_opts())
     if self.get_Urls().__len__() > 0:
         ydl1.download(self.get_Urls())

def downloadVideoThrd(self):
    self.t1 = threading.Thread(target=self.download_videos())
    self.t1.start()
Run Code Online (Sandbox Code Playgroud)

python multithreading python-3.x youtube-dl

5
推荐指数
1
解决办法
2228
查看次数

从另一个线程调用一个扭曲的协议方法

我用Python创建了一个Home Security程序,它使用Raspberry Pi的GPIO来感知运动并启动警报器.用户使用NFC标签激活/停用系统,也可以连接到覆盆子pi的nfc reder.

为此,我需要不间断地检查nfc标签,同时不断检查传感器的运动是否也无阻塞.我需要一些更平行的东西,但我认为这两个足以说明问题.

现在我使用我开始/ 停止的线程 - 在一段时间后停止线程 - 我不确定这是否是最佳方式,但截至目前系统工作正常.

现在我想扩展其功能,通过websockets提供通知.我发现这可以用Twisted完成,但我很困惑..

以下是我尝试执行此操作的示例代码:

from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, \
                               WebSocketServerProtocol, \
                               listenWS


def thread1(stop_event):
    while(not stop_event.is_set()):
        stop_event.wait(4)
        print "checking sensor"
        # sensor_state = GPIO.input(11)
        if sensor_state == 1:
            # how can I call send_m("sensor detected movement")  #<---
            t1_stop_event.set()

t1_stop_event = Event()
t1 = Thread(target=thread1, args=(t1_stop_event,))

class EchoServerProtocol(WebSocketServerProtocol):
   def onMessage(self, msg, binary):
    print "received: "+msg
    print "stopping thread1"
    t1_stop_event.set()

   def send_m(self, msg):
    self.sendMessage(msg)

if __name__ == '__main__':
   t1.start() …
Run Code Online (Sandbox Code Playgroud)

python multithreading twisted websocket

4
推荐指数
1
解决办法
2803
查看次数

如何杀死这个threading.Timer?

我已经使用一个Timer对象启动了一个线程.现在,我想停止这个线程,但我不能.我用过cancel(),但它不起作用.我不知道为什么.

import threading
import time
import sys as system
def Nop():
    print("do nothing")
    return 0
def function():
    try:
        while True:
            print("hello world ")
            time.sleep(2)
    except KeyboardInterrupt:
            print( "Good job!! exception catched") 
t = threading.Timer(10, function)
t.start()
print(t.getName)
counter = 0
while True:
    try:
        time.sleep(1) 
        Nop()
        counter = counter +1
        print(counter)
        if counter == 20:
            print(t.getName)
            t.cancel()
            counter = 0
            break
        if t.is_alive() == False:
            print("The Timer thread is dead...")
    except KeyboardInterrupt:
        print("End of program")
        t.cancel()
        system.exit(0) …
Run Code Online (Sandbox Code Playgroud)

python multithreading timer

2
推荐指数
1
解决办法
7584
查看次数