Python多线程帮助

2024-10-01 10:21:51 发布

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

我希望在一个新线程中从另一个python脚本中调用一个python函数。 我有使用经验子流程.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

Tags: 模块函数命令行脚本maindef经验流程
1条回答
网友
1楼 · 发布于 2024-10-01 10:21:51

这里有一个解决方案,但它并不像你所要求的那样,因为杀死一个线程很复杂。最好让线程自行终止,所有线程默认为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导入多处理并将threading.Thread(切换到{},那么其他的一切都保持不变。在

相关问题 更多 >