【发布时间】:2013-04-29 14:20:48
【问题描述】:
我有几个线程,每个线程都在更改工作目录,偶尔会在特定工作目录中创建新目录,在这些目录中复制/移动文件等。想想例如:
def thread1:
while True:
os.chdir('dir')
os.mkdir('newdir')
os.system('mv *.png newdir/')
do something
def thread2:
while True:
os.chdir('another-dir')
os.mkdir('another-newdir')
os.system('mv *.png another-newdir/')
do something
我读过 chdir、mkdir 函数不是特定于线程而是全局的。有什么方法可以做到这一点?我可以尝试使用绝对路径,但这是最好的解决方案吗?
【问题讨论】:
-
解决这个问题的快速方法是永远不要打电话给
os.chdir()。在您的情况下,它将变为os.mkdir('dir/newdir'); os.system('cd dir && mv *.png newdir/')。请注意,cd在 shell 命令中。 -
另一种解决方案——仅在 Linux 上——是使用
unshare(CLONE_FS)函数,但这肯定需要编写 C 或使用 ctypes/cffi。
标签: python multithreading operating-system