python - specifically handle file exists exception

后端 未结 2 1408
一向
一向 2021-02-05 05:05

I have come across examples in this forum where a specific error around files and directories is handled by testing the errno value in OSError (or

2条回答
  •  孤城傲影
    2021-02-05 05:25

    Here's an example of dealing with a race condition when trying to atomically overwrite an existing symlink:

    # os.symlink requires that the target does NOT exist.
    # Avoid race condition of file creation between mktemp and symlink:
    while True:
        temp_pathname = tempfile.mktemp()
        try:
            os.symlink(target, temp_pathname)
            break  # Success, exit loop
        except FileExistsError:
            time.sleep(0.001)  # Prevent high load in pathological conditions
        except:
            raise
    os.replace(temp_pathname, link_name)
    

提交回复
热议问题