Ank
Ank

Reputation: 6270

python subprocess deleting and renaming files

I am trying to delete a file, then rename a file to the deleted file in python.

import sys
import subprocess
fileInput = sys.argv[1]
|
|
#code to create fileInput.tmp
|
|
ret=subprocess.Popen("rm "+fileInput,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print ret
ret1=subprocess.Popen("mv "+ fileInput+".tmp "+fileInput,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print ret1

Whats happening is sometimes (not always) both fileInput and fileInput.tmp are being deleted in "ret=" step and "ret1=" step doesn't execute.

Can someone suggest why is it happeing. This code is run on MacOSx

Upvotes: 0

Views: 5196

Answers (2)

Michał Górny
Michał Górny

Reputation: 19243

Ok, not answering the question directly but providing a better alternative.

Using subprocess here is a very bad idea. It is very easy here to end up doing horrible things; you'll at least need to escape the arguments passed to shell.

Instead, use what Python gives you:

os.rename(fileInput + '.tmp', fileInput)

This is the atomic move/rename operation. And you don't have to rm file before replacing it. Moreover, you usually don't do that because between the rm and mv calls there will be no file with that name. If you just use mv, the replacement will be atomic and some file will always be there.

That's all the short story, I think.


As a side note, os.rename() doesn't work across filesystems. So while using it for renaming a file is ok (the source and destination are in the same directory), if you're moving files across different directories you'd rather use:

import shutil

shutil.move(src, dst)

Upvotes: 3

Ali Afshar
Ali Afshar

Reputation: 41643

The first subprocess is not completing, do this:

p = subprocess.Popen("...")
p.communicate() # waits until the subprocess completes

Upvotes: 2

Related Questions