2012-03-08 71 views
1

在Windows 7 Pro 64位上运行Python 3.2。Python线程支持脚本的其余部分

好的我在这里有一些非常基本的代码,这只是表现得不像我想要的那样。

#!/usr/bin/env python 

import time 
import threading 

def shutdown(sleeptime): 
    time.sleep(sleeptime) 
    print('I have executed') 

threading.Thread(target = shutdown(5)).start() 
print('I go first') 

的想法是,脚本运行时,它开始其休眠5秒钟,然后打印出“我已执行”的线程。与此同时,脚本继续前进并打印出“我先走了”。

实际情况是脚本启动线程,一切都等待它完成,然后继续。显然,我不是在做正确的线程,但我无法找到线程的简单示例与Python 3

回答

10

你声明:

threading.Thread(target = shutdown(5)).start() 

可以等效写成:

x = shutdown(5) 
threading.Thread(target = x).start() 
即,

也就是说您先调用shutdown,然后将结果传递给Thread构造函数。

你需要通过你的功能,无需调用它,你的参数列表,分别螺纹:

threading.Thread(target = shutdown, args = (5,)).start() 
+0

谢谢,优秀和良好解释的答案! – Sparc 2012-03-08 21:42:57

2

你的目标不是评价的功能,而是关机的值(5)这是None。你可能想要它更像︰

def shutdown(sleeptime): 
    def shutter_downer(): 
     time.sleep(sleeptime) 
     print('I have executed') 
    return shutter_downer