Reputation: 21
I want to remove all the files and directories except for some of them by using
`subprocess.call(['rm','-r','!(new_models|creat_model.py|my_mos.tit)'])`
but it gives back information
rm: cannot remove `!(new_models|creat_model.py|my_mos.tit)': No such file or directory
how can I fix this? Thanks
Upvotes: 2
Views: 14503
Reputation: 139
Code to remove all png
args = ('rm', '-rf', '/path/to/files/temp/*.png')
subprocess.call('%s %s %s' % args, shell=True)
Upvotes: 0
Reputation: 91059
An alternative to shell=True
could be the usage of glob
and manual filtering:
import glob
files = [i for i in glob.glob("*") if i not in ('new_models', 'creat_model.py', 'my_mos.tit')]
subprocess.call(['rm','-r'] + files)
Edit 4 years later:
Without glob (of which I don't remember why I suggested it):
import os
files = [i for i in os.listdir() if i not in ('new_models', 'creat_model.py', 'my_mos.tit')]
subprocess.call(['rm','-r'] + files)
Upvotes: 2
Reputation: 4679
If you use that rm
command on the command line the !(…|…|…)
pattern is expanded by the shell into all file names except those in the pattern before calling rm
. Your code calls rm
directly so rm
gets the shell pattern as a file name and tries to delete a file with that name.
You have to add shell=True
to the argument list of subprocess.call()
or actually code this in Python instead of calling external commands. Downside: That would be more than one line. Upside: it can be done independently from external shells and system dependent external programs.
Upvotes: 6