如何为threading.Thread和multiprocessing.Pool指定本地工作目录? [英] How to specify a local working directory for threading.Thread and multiprocessing.Pool?

查看:94
本文介绍了如何为threading.Thread和multiprocessing.Pool指定本地工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just like subprocess.Popen( target=, cwd=), it can specify its own local working directory. I dont want to specify the absolute path every time because simple is better than complex. os.chdir() doesn't work at all since it sets a global variable (right?). Whenever there are multiple threads, os.chdir() will fail. Any suggestions? Thank you!

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

I just try jorgenkg's code and modify a little bit and you may see why I have to ask this question. Here is the code.

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不再在其原始工作目录上工作.

You can see that Thread-2 is no long working on its original working directory after os.chdir() is invoked.

推荐答案

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

As you state, the current directory path belongs to the process that owns the threads

在初始化将共享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() .

As above, once the directory is changed, all threads change with it. Hence, you cannot use os.chdir() concurrently across multiple threads.

这篇关于如何为threading.Thread和multiprocessing.Pool指定本地工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆