python / python/cpython

shutil's move function fails to handle files opened by another process

Abierto
#120,882 0 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

OS-windows type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
36k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug report

Bug description:

Problem:

When attempting to move a file using shutil.move from one location to another, if the file is opened by another process (if file is opened in other python script using open function), shutil.move raises an error (WinError 32: The process cannot access the file because it is being used by another process). Despite this error, the file is still copied to the destination directory, which is unexpected behavior.

Details:

The shutil.move function is designed to handle moving files or directories between locations. However, it does not check if the file is currently open by another process before attempting to move it. This results in an error being raised, but the file is still copied to destination regardless of the error condition.

Solution:

To address this issue, I modified the shutil.move function to include an additional check for OSError with errno.EACCES (Permission Denied) in the exception handling block. This ensures that if the file cannot be moved due to being opened by another process, the operation is aborted cleanly without copying the file to maintain the integrity of the move function as well as file system.

Here is the modified part of the shutil.move function

    except OSError as exc:
        if exc.errno == errno.EACCES:
            raise  # Propagate the PermissionError
     # Existing code

Proposal:

I propose adding this error handling improvement to the shutil.move function in Python's standard library. This enhancement will make file operations more reliable in scenarios where files may be concurrently accessed by multiple processes

Steps to Reproduce:

  • Open a file (test.pdf) in any python script using open function in read mode.
  • Attempt to move the file using shutil.move to another directory.
  • Observe the WinError 32 exception and incorrect copying behavior.
  • Close the file (To avoid memory leakage).

NOTE: Avoid to use context manager here for opening file to find the error.
You can also run the following script to get the error.

import shutil

src = "C://Users//Desktop//Downloads//test.pdf" # Provide full file path of your system.
dst_dir = "D://Files" # Provide destination directory path.
f = open(src, "r")
try:
    shutil.move(src, dst_dir)
except Exception as e:
    print(e)
finally:
    f.close()

Expected Behavior:

When shutil.move encounters a situation where the source file is open in another process (WinError 32), it should raise an exception and abort the operation without performing any partial file copying to the destination.

Impact:

This issue affects users trying to use shutil.move to relocate files that are concurrently accessed by other processes. The proposed solution aims to improve the robustness and expected behavior of the function in such scenarios.

CPython versions tested on:

3.10

Operating systems tested on:

Windows

Linked PRs
  • gh-120883

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en el punto de entrada shutil.move y reproduce el comportamiento de Windows informado con un archivo de origen mantenido abierto por otro proceso. Verifica que la operación genere la excepción esperada sin dejar un archivo de destino copiado, y revisa el PR vinculado gh-120883 antes de comenzar, porque ya hay trabajo asociado a este issue.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
operating-systems
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.