python-如何为threading.Thread和multiprocessing.Pool指定本地工作目录?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何为threading.Thread和multiprocessing.Pool指定本地工作目录?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1736字,纯文字阅读大概需要3分钟。
内容图文
![python-如何为threading.Thread和multiprocessing.Pool指定本地工作目录?](/upload/InfoBanner/zyjiaocheng/678/9c773e7421fb41b8a869a97c162b1730.jpg)
就像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 "/"
这是结果.
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()之后,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 "/"
As above, once the directory is changed, all threads change with it. Hence, you cannot use
os.chdir()
concurrently across multiple threads.
内容总结
以上是互联网集市为您收集整理的python-如何为threading.Thread和multiprocessing.Pool指定本地工作目录?全部内容,希望文章能够帮你解决python-如何为threading.Thread和multiprocessing.Pool指定本地工作目录?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。