Python 如何为threading.Thread和multiprocessing.Pool指定本地工作目录?
与subprocess.Popen(target=,cwd=)一样,它可以指定自己的本地工作目录。 我不想每次都指定绝对路径,因为简单比复杂好。 chdir()根本不起作用,因为它设置了一个全局变量(对吗?)。只要有多个线程,os.chdir()就会失败。 有什么建议吗?谢谢大家! 我只是尝试一下jorgenkg的代码并稍加修改,您可能会明白我为什么要问这个问题。这是代码Python 如何为threading.Thread和multiprocessing.Pool指定本地工作目录?,python,multiprocessing,Python,Multiprocessing,与subprocess.Popen(target=,cwd=)一样,它可以指定自己的本地工作目录。 我不想每次都指定绝对路径,因为简单比复杂好。 chdir()根本不起作用,因为它设置了一个全局变量(对吗?)。只要有多个线程,os.chdir()就会失败。 有什么建议吗?谢谢大家! 我只是尝试一下jorgenkg的代码并稍加修改,您可能会明白我为什么要问这个问题。这是代码 import os import threading import time class child(threading.
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() + '\r\n'
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:\Python27\Projects
I am Thread-2 in C:\
I am Thread-1 in C:\
I am Thread-2 in C:\
您可以看到,调用os.chdir()后,线程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()
。请参阅我的更新信息,一旦使用os.chdir()更改工作目录,所有线程的工作目录都将更改。但是我希望每个线程都有自己的工作目录。这是正确的!但是不可能定义一个通用的工作目录,这不是通用的!进程拥有workingdir变量,但是如果线程调用os.chdir
,它可以创建自己的workingdir。如果我没弄错的话,你所希望的是不可能的。一个可能对你有帮助的黑客,就是给你的线程类
提供一个路径变量。我是写作课的新手。如何将路径输入到inipath?这非常简单,请查看上面更新代码中的第13行!