Python 多线程帮助

0 投票
1 回答
2971 浏览
提问于 2025-04-16 20:31

我想在一个Python脚本里,从另一个Python脚本中调用一个函数,并且希望这个调用是在一个新的线程里进行。我之前用过subprocess.Popen这个方法,但那是用来在命令行中调用.exe文件的。有没有人推荐一下怎么做,或者有什么模块可以使用?

def main(argv):
    call otherdef(1,2,3) in a new thread
    sleep for 10 minutes
    kill the otherdef process

def otherdef(num1, num2, num3):
    while(True):
        print num1

1 个回答

3

这里有一个解决方案,不过和你问的有点不一样,因为结束一个线程其实挺复杂的。更好的办法是让线程自己结束。所有线程默认是非守护线程(daemonic=False),除非它的父线程是守护线程。所以当主线程结束时,你的线程会继续运行。如果把它设置为守护线程(daemonic=True),那么它就会和主线程一起结束。

基本上,你只需要启动一个 Thread,并给它一个要运行的方法。你需要能够传递参数,所以你可以看到我用 args= 参数传递了要给目标方法的值。

import time
import threading


def otherdef(num1, num2, num3):
    #Inside of otherdef we use an event to loop on, 
    #we do this so we can have a convent way to stop the process.

    stopped = threading.Event()
    #set a timer, after 10 seconds.. kill this loop
    threading.Timer(10, stopped.set).start()
    #while the event has not been triggered, do something useless
    while(not stopped.is_set()):
        print 'doing ', num1, num2, num3
        stopped.wait(1)

    print 'otherdef exiting'

print 'Running'
#create a thread, when I call start call the target and pass args
p = threading.Thread(target=otherdef, args=(1,2,3))
p.start()
#wait for the threadto finish
p.join(11)

print 'Done'    

现在还不太清楚你想要的是进程还是线程,不过如果你想要一个 Process,只需导入 multiprocessing,然后把 threading.Thread( 改成 multiprocessing.Process(,其他的都保持不变。

撰写回答