Python 多线程帮助 [英] Python Multi-threading Help

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

问题描述

我希望在新线程中从另一个 python 脚本中调用 python 函数.我有使用 subprocess.Popen 的经验,但我用它来在命令行中调用 .exe.有人推荐如何执行此操作或使用模块吗?

I'm looking to call a python function from within another python script in a new thread. I have experience using subprocess.Popen, but I used that for calling .exe's in the command line. Anyone recommend how to do this or a module to use?

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

推荐答案

这里有一个解决方案,但它并不完全像你问的那样,因为杀死一个线程很复杂.最好让线程自行终止,所有线程默认为 daemonic=False(除非其父线程是守护线程),因此当主线程死亡时,您的线程将继续存在.将其设置为 true,它将随着您的主线程而死亡.

Here is a solution, but its not exactly like you asked, because its complicated to kill a thread. Its better to let the thread terminate itself, all threads default to daemonic=False (unless its parent thread is daemonic), so when the main thread dies, your thread would live. Set it to true, and it will die with your main thread.

基本上你要做的就是启动一个 Thread 并给它一个运行方法.您需要能够传递参数,以便您可以看到我传递了一个 args= 参数,其中包含要传递给目标方法的值.

Basically all you do is launch a Thread and give it a method to run. You needed to be able to pass arguments so as you can see I pass an args= parameter with the values to pass to the target method.

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(,其他一切保持不变.


Its still unclear if you want a process or a thread, but if you want a Process import multiprocessing and switch threading.Thread( to multiprocessing.Process(, everything else stays the same.

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

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