操作系统chdir()导致了python多线程的意外行为

2024-09-24 06:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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”目录,创建“你好.txt在“hiDir1”内打印“Hello Andrew”你好.txt““
  2. thread2:创建“hiDir2”目录,创建“你好.txt在“hiDir2”内打印“Hello Michael”你好.txt““

当我第一次运行代码时,它没有出错。所有文件均正确生成。但是“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线程模块中的错误吗?你知道吗

谢谢。你知道吗


Tags: inpyselftxtoslinefilesayhello
1条回答
网友
1楼 · 发布于 2024-09-24 06:31:31

这个怎么样:

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

相关问题 更多 >