Python 不同参数的线程化 (Python 2.4.3)

Python Threading with varying arguments (Python 2.4.3)

我正在学习 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) 次时打印 "filename"。但是,我想将列表文件中的文件名作为参数传递给函数。我应该怎么办?

您应该在 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]