如何为线程指定本地工作目录.线程和多处理.水塘



就像子流程一样。Popen(target=,cwd=),它可以指定自己的本地工作目录。我不想每次都指定绝对路径,因为简单总比复杂好。os.chdir()根本不起作用,因为它设置了一个全局变量(对吗?)。只要有多个线程,os.chdir()就会失败。有什么建议吗?非常感谢。

我只是尝试了jorgenkg的代码,并进行了一点修改,你可能会明白我为什么要问这个问题。这是代码。

import os
import threading
import time
class child(threading.Thread):
    def run(self ):
        for i in range(1,3):
            print "I am " + str(threading.current_thread())[7:15] + " in " + os.getcwd() + 'rn'
            time.sleep(2)            

child().start() # prints "/username/path"

os.chdir('C://') # The process is changing directory
child().start() # prints "/"

这是结果

I am Thread-1 in C:Python27Projects
I am Thread-2 in C:

I am Thread-1 in C:
I am Thread-2 in C:

您可以看到,调用os.chdir()后,Thread-2不再在其原始工作目录上工作。

正如您所说,当前目录路径属于拥有线程的进程。

在创建线程之前,必须在初始化将共享os.getcwd()的子线程之前设置路径。下面是一个简单的代码示例:

import os
import threading
import time
class child(threading.Thread):
    def __init__(self, initpath=None):
        # initpath could be a string fed to many initializations
        time.sleep(0.05) # print() doesn't seem thread safe, this delays it.
        super(child, self).__init__()
        if initpath is not None:
            os.chdir(initpath)
    def run(self):
        print(os.getcwd())
        time.sleep(2)
        print("slept "+os.getcwd())  # These will all show the last path.
child().start() # Prints your initial path.
# Both print "/home/username/path/somefolder/".
child(initpath="/home/username/path/somefolder/").start() 
child().start()
os.chdir("/") # The process is changing directory
child().start() # prints "/"

如上所述,一旦目录更改,所有线程都会随之更改。因此,不能在多个线程之间同时使用os.chdir()

最新更新