Search code examples
pythonmultithreadingpython-2.7filepython-multithreading

python 2.7.6 threading on Windows 10 : The process cannot access the file because it is being used by another process


I have a Python 2.7.6 script that will launch threads (inheriting from threading.Thread) of execution in parallel. Each will access thread-specific files and output some logs there.

However in my main console, I sometimes get a message "The process cannot access the file because it is being used by another process.". I do not know from which thread it came from or which file is being mentioned here.

How can I go about inquiring ?


Solution

  • Process Monitor should be able to help.

    Add the following filters:

    • Process Name - contains - python - Include, because you use Python
    • Result - is - SUCCESS - Exclude, because you're interested in errors
    • Result - is - BUFFER OVERFLOW - Exclude, because buffer overflows are normal (the buffer will be increased and the read operation will be retried)

    Thus you should be able to find the sharing violation:

    Sharing violation

    Now that you know what you're looking for, you can of course define a much simpler filter:

    • Result - is - SHARING VIOLATION - Include

    Code for testing the settings before applying them in production:

    import shutil
    with open("test.txt", "wb") as file:
        shutil.move("test.txt", "test2.txt")
    

    Double clicking on the entry should give you the thread ID and file name:

    Details