2016-12-30 37 views
1

看一看這段代碼:如何在python中使用線程時創建文件?

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) 

用幹my_inline_function(),這將啓動一個線程,而不是創建一個文件?

但是,當我直接調用function_that_writes(...)(不在線程中運行)時,它能夠創建一個文件。

爲什麼我得到這種行爲?

回答

0

您需要提供您的參數作爲一個元組args=(number,)

download_thread = threading.Thread(target=function_that_writes, args=(number,)) 

唯一的例外是在這裏很清楚:

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 
+0

是的,你說得對,但爲什麼我沒有收到錯誤消息? –

+0

你是否從命令行運行你的腳本?你在使用什麼操作系統? –

+0

Ubuntu和我從pycharm運行這個 –