gpt4 book ai didi

python - os.chdir() 导致 python 多线程出现意外行为

转载 作者:太空宇宙 更新时间:2023-11-03 21:11:59 24 4
gpt4 key购买 nike

我是 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()

预期行为是,

  1. thread1 : 创建“hiDir1”目录,在“hiDir1”内创建“hello.txt”并在“hello.txt”中打印“Hello Andrew”
  2. thread2 : 创建“hiDir2”目录,在“hiDir2”中创建“hello.txt”并在“hello.txt”中打印“Hello Michael”

当我第一次运行代码时,它运行时没有错误。所有文件均已正确生成。但“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”的文本文件具有正确的输出。 “hiDir2”为空。出现以下错误消息。

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()

然后就没有问题了。代码按预期运行。 python多线程中使用os.chdir()有什么问题吗?这是 python 线程模块中的错误吗?

谢谢。

最佳答案

这个怎么样:

import threading

from pathlib import Path


def say_hello(dir_name, username):
"""
Creates dir_name (and its parents dirs) if not dir_name does not exist,
then it creates a hello.txt file with the legent: 'Hello <username>'

Examples:

>>> say_hello('say_hello/slackmart', 'SLACKMART')
say_hello/slackmart not found. Creating say_hello/slackmart
Writing to say_hello/slackmart/hello.txt
"""
path = Path(dir_name)
if not path.exists():
print(f'{dir_name} not found. Creating {dir_name}')
path.mkdir(parents=True)
else:
# I wouldn't remove the dir_name path here as it could be dangerous
print(f'Found {dir_name}')

file_path = path / Path('hello.txt') # Yes, you can join paths by using /
print('Writing to', file_path)
file_path.write_text(f'Hello {username}\n')


if __name__ == '__main__':
andrew = threading.Thread(target=say_hello, args=('hiAndrewDir', 'Andrew'))
michael = threading.Thread(target=say_hello, args=('hiMichaelDir', 'Michael'))

andrew.start()
michael.start()

andrew.join()
michael.join()

演示时间:

$ python3 sayhello.py

https://docs.python.org/3/library/pathlib.html

关于python - os.chdir() 导致 python 多线程出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55003876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com