Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, how do I close a file in use by another user over a network?

Tags:

python

file-io

I have a program that creates a bunch of movie files. I runs as a cron job and every time it runs the movies from the previous iteration are moved to a 'previous' folder so that there is always a previous version to look at.

These movie files are accessed across a network by various users and that's where I'm running into a problem.

When the script runs and tries to move the files it throws a resource busy error because the files are open by various users. Is there a way in Python to force close these files before I attempt to move them?

Further clarification:

JMax is correct when he mentions it is server level problem. I can access our windows server through Administrative Tools > Computer Management > Shared Folders > Open Files and manually close the files there, but I am wondering whether there is a Python equivalent which will achieve the same result.

something like this:

try:

    shutil.move(src, dst)

except OSError:

  # Close src file on all machines that are currently accessing it and try again.  
like image 202
Daniel Lloyd-Wood Avatar asked Apr 29 '26 06:04

Daniel Lloyd-Wood


1 Answers

This question has nothing to do with Python, and everything to do with the particular operating system and file system you're using. Could you please provide these details?

At least in Windows you can use Sysinternals Handle to force a particular handle to a file to be closed. Especially as this file is opened by another user over a network this operation is extremely destabilising and will probably render the network connection subsequently useless. You're looking for the "-c" command-line argument, where the documentation reads:

Closes the specified handle (interpreted as a hexadecimal number). You must specify the process by its PID.

WARNING: Closing handles can cause application or system instability.

And if you're force-closing a file mounted over Samba in Linux, speaking from experience this is an excruciating experience in futility. However, others have tried with mixed success; see Force a Samba process to close a file.

like image 183
Asim Ihsan Avatar answered Apr 30 '26 20:04

Asim Ihsan