作为线程返回给调用者(不要这样做)

2024-09-30 01:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个检查文件更改的函数。
每次它发现一个变化,它就会启动一个线程并将流返回给调用者。你知道吗

def if_file_changes(file_loc):
    import threading, time 
    with open(file_loc, 'r') as nctn:
        state = nctn.read()
    while True:
        time.sleep(5)
        with open(file_loc, 'r') as nctn:
            check_state = nctn.read()
        if check_state != state:
            state = check_state
            check_state = None
            t = threading.Thread(return) # How do I return in a thread?
            t.daemon = True
            t.start()

编辑:
我不明白这个问题。我试图在函数级创建线程,而它本应在调用者处创建。
我的解决方案如下。你知道吗


Tags: 函数readiftimecheckaswithopen
2条回答

通过在新线程中设置全局值,可以实现返回线程

G_THREAD_RET = None

def thread_func():
    #do something here
    G_THERAD_RET = ret

def main():
    #this is the main thread function
    # wait for child thread here
    ret = G_THERAD_RET # get the return value of child thread

如果只有几个线程可以从中获取返回值,那么这是最简单的。你知道吗

此外,还可以将param传递给thread函数,并在线程退出之前在新线程中设置它:

def func(ret=[]):
    time.sleep(2)
    ret.append(2)

def main():
    ret = []
    t = threading.Thread(target=func,args=(ret,))
    t.start()
    t.join()
    print ret

必须使用list来返回值,因为在python中只有list和dict是可变的。你知道吗

PS:你真的需要阅读整个文件来检查是否有一些变化吗?检查时间戳对于检测文件更改更为常见。你知道吗

我所做的更正是将调用者模块化为函数,以便根据需要重复任何部分。然后导入文件检查器并在需要时调用它。你知道吗

函数:

def on_file_change(func=None, file_loc=None, start_activated=False):
    import threading, time
    def s():
        with open(file_loc, 'r') as nctn:
            state = nctn.read()
        while True:
            time.sleep(5)
            with open(file_loc, 'r') as nctn:
                check_state = nctn.read()
            if check_state != state and check_state != None and check_state != '':
                state = check_state
                t = threading.Thread(target=func)
                t.start()
    if start_activated == True:
        t = threading.Thread(target=func)
        t.start()
    s()

相关问题 更多 >

    热门问题