[英]How to create a file when working with threads in python?
Have a look at this code : 看看这段代码:
import threading
import time
def my_inline_function(number):
#do some stuff
download_thread = threading.Thread(target=function_that_writes, args=number)
download_thread.start()
#continue doing stuff
i = 0
while(i < 10000):
print str(i) + " : Main thread"
time.sleep(1)
i = i + 1
def function_that_writes(number):
i = number
file = open("dummy.txt", 'w')
while (i < 10000):
string = str(i) + " : child thread"
file.write(string)
time.sleep(1)
file.close()
my_inline_function(5)
function_that_writes(5)
With does my_inline_function()
, which starts a thread, not create a file? 使用启动线程的my_inline_function()
,而不是创建文件?
But when I am calling a function_that_writes(...)
directly, which is not running in a thread, it is able to create a file. 但是当我直接调用一个没有在线程中运行的function_that_writes(...)
,它能够创建一个文件。
Why am I getting this behaviour? 为什么我会出现这种行为?
You need to supply your argument as a tuple args=(number,)
: 你需要提供你的参数作为元组args=(number,)
:
download_thread = threading.Thread(target=function_that_writes, args=(number,))
The exception is pretty clear here: 这个例外很清楚:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Users/mike/anaconda/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/Users/mike/anaconda/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: function_that_writes() argument after * must be an iterable, not int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.