簡體   English   中英

在python中使用線程時如何創建文件?

[英]How to create a file when working with threads in 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(...) ,它能夠創建一個文件。

為什么我會出現這種行為?

你需要提供你的參數作為元組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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM