0

确定在一个线程中使用 os.chdir 更改当前目录是否会更改在调用 os.chdir 之前已经存在的线程的当前目录的程序 我的问题是如何获取活动线程的值?

import threading
import time
import os
class MyThread(threading.Thread):
def __init__(self, *args, **kw):
    threading.Thread.__init__(self, *args, **kw)
    self.sleeptime = 2
def run(self):        
    for i in range(self.sleeptime):
        for j in range(500000):
            k = j*j
        print(self.name, "finished pass", i)
    print(self.name, "finished after", self.sleeptime, "seconds")

bgthreads = threading.active_count()
threadOne = os.chdir("V:\\workspace\\Python4_Homework10")
threadTwo = os.chdir("V:\\workspace")
threadThree = os.chdir("V:")
tt = [MyThread(threadOne), MyThread(threadTwo), MyThread(threadThree)]
for t in tt:    
   t.start()

print("Threads started")
while threading.active_count() > bgthreads:
    time.sleep(2)
    print("tick")
4

1 回答 1

0

这有点粗糙,但这可能会完成你的工作。

#!/usr/bin/env python3

import os
import threading

def threadReporter(i,name):
    if name == 'Thread-changer': # crude, but gets the job done for this
        os.chdir('/tmp')
    print("{0} reports current pwd is: {1}".format(name,os.getcwd()))

if __name__ == '__main__':
    # create pre-chdir and changer Thread
    t_pre = threading.Thread(target=threadReporter, args=(1,'Thread-pre'))
    t_changer = threading.Thread(target=threadReporter, args=(2,'Thread-changer'))

    # start changer thread
    t_changer.start()
    # wait for it to finish
    t_changer.join()

    # start the thread that was created before the os.chdir() call
    t_pre.start()

    # create a thread after the os.chdir call and start it
    t_post = threading.Thread(target=threadReporter, args=(3,'Thread-post'))
    t_post.start()

正如 gps 上面已经指出的那样,当前工作目录是进程全局的,并且对于可能产生/运行的每个线程都不是分开的。因此,上面程序中当前工作目录的报告对于每个运行的线程都是相等的,无论线程是何时创建的。在 os.chdir() 之后,为所有线程设置了新的工作目录。

于 2012-06-27T09:25:01.860 回答