Ken*_*n T 8 python multiprocessing
就像 subprocess.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() + '\r\n'
time.sleep(2)
child().start() # prints "/username/path"
os.chdir('C://') # The process is changing directory
child().start() # prints "/"
Run Code Online (Sandbox Code Playgroud)
这是结果。
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:\
Run Code Online (Sandbox Code Playgroud)
您可以看到,在调用 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 "/"
Run Code Online (Sandbox Code Playgroud)
如上所述,一旦目录更改,所有线程都会随之更改。因此,您不能os.chdir()跨多个线程同时使用。
| 归档时间: |
|
| 查看次数: |
5525 次 |
| 最近记录: |