使用不同参数的Python线程(Python 2.4.3)

时间:2015-10-06 16:36:26

标签: python multithreading centos python-multithreading

我正在学习python中的线程和并发部分,我选择了一个示例,我在其中os.walk()从目录中获取文件列表,使用os.path.join()将其填充到数组中然后使用线程来更改这些文件的所有权。这个脚本的目的是学习线程。我的代码是

for root, dir, file in os.walk("/tmpdir/"):
    for name in file:
        files.append(os.path.join(root, name))

def filestat(file):
    print file ##The code to chown will go here. Writing it to just print the file for now.

thread = [threading.Thread(target=filestat, args="filename") for x in range(len(files))]
print thread ##This will give me the total number of thread objects that is created
for t in thread:
    t.start() ##This will start the thread execution

这将打印"文件名"执行len(files)次时。但是,我想将列表文件中的文件名作为参数传递给函数。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您应该使用您在args参数内迭代的变量名称。别忘了把它变成一个元组。

thread = [threading.Thread(target=filestat, args=(files[x],)) for x in range(len(files))]

或者

thread = [threading.Thread(target=filestat, args=(filename,)) for filename in files]