我对Python中的多线程还不熟悉。在我的代码中,我调用了一个函数,该函数使用chdir()更改其工作目录,如下所示。你知道吗
import threading
import os
import shutil
def sayHello(dirName,userName):
if not os.path.exists(dirName):
os.makedirs(dirName)
else:
shutil.rmtree(dirName)
os.makedirs(dirName)
os.chdir(dirName)
f = open("hello.txt","w")
f.write("Hello %s\n" %userName)
f.close()
thread1 = threading.Thread(target=sayHello,args=('hiDir1','Andrew'))
thread2 = threading.Thread(target=sayHello,args=('hiDir2','Michael'))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
预期的行为是
当我第一次运行代码时,它没有出错。所有文件均正确生成。但是“hiDir2”在“hiDir1”里面。你知道吗
没有删除生成的文件,我第二次运行了它。两个目录都在那里。但只有“hiDir2”有正确的文本文件和正确的信息打印文件hiDir1“没有文本文件。弹出以下错误。你知道吗
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "threadingError.py", line 9, in sayHello
shutil.rmtree(dirName)
File "/usr/lib/python3.5/shutil.py", line 478, in rmtree
onerror(os.rmdir, path, sys.exc_info())
File "/usr/lib/python3.5/shutil.py", line 476, in rmtree
os.rmdir(path)
FileNotFoundError: [Errno 2] No such file or directory: 'hiDir1'ode here
当我第三次运行它而不删除文件时,第二次运行的情况正好相反。两个目录都在那里。但只有“hiDir1”有正确输出的文本文件“隐藏2”是空的。出现以下错误消息。你知道吗
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "threadingError.py", line 12, in sayHello
os.chdir(dirName)
FileNotFoundError: [Errno 2] No such file or directory: 'hiDir2'
当我反复运行这个程序时,第二次和第三次出现的次数正好是一个接一个的(怎么会发生这种情况呢?它每次的输出应该是一样的,不是吗?)你知道吗
据我所知,问题在于'chdir()'。所以我重新整理了代码,去掉了chdir(),如下所示。你知道吗
import threading
import os
import shutil
def sayHello(dirName,userName):
if not os.path.exists(dirName):
os.makedirs(dirName)
else:
shutil.rmtree(dirName)
os.makedirs(dirName)
filePath1 = dirName+'/hello.txt'
print("filePath1: ", filePath1)
# os.chdir(dirName)
f = open(dirName+'/hello.txt',"w")
f.write("Hello %s\n" %userName)
f.close()
thread1 = threading.Thread(target=sayHello,args=('hiDir1','Andrew'))
thread2 = threading.Thread(target=sayHello,args=('hiDir2','Michael'))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
然后,就没有问题了。代码按预期运行。有什么问题吗操作系统chdir()在python多线程中使用时?这是python线程模块中的错误吗?你知道吗
谢谢。你知道吗
这个怎么样:
演示时间:
https://docs.python.org/3/library/pathlib.html
相关问题 更多 >
编程相关推荐