2

I am trying to remove some file (from my linux machine), except few:

touch INCAR KPOINTS foo bar
$ls
bar  foo  INCAR  KPOINTS
$python3 mini.py
Job Done
$ls
bar  foo  INCAR  KPOINTS 

The mini.py is:

#!/usr/bin/python3
import subprocess

subprocess.run(['rm', '-f', '!(INCAR|KPOINTS|PO*|*.sh)'])
print("Job Done")

As can be seen in the output of mini.py, its notgiving any error but neither its doing its job.

What I am doing wrong here?

6
  • rm is not a executable, it's just a internal command of bash. Try run['bash', '-c', " rm ..."] Commented Jun 16, 2016 at 17:24
  • thats not working either Commented Jun 16, 2016 at 17:34
  • 2
    rm is an executable in any sane system. It is part of the GNU Coreutils package and you can find it in /bin/ or /usr/bin depending on your distro. Commented Jun 16, 2016 at 17:35
  • 1
    sorry, I was wrong. But why don't you use os.remove(). It seems that the rm runs but cannot delete some of those files. Commented Jun 16, 2016 at 17:44
  • can I select which files NOT to dellete with os.remove? I mean !(...) part? Commented Jun 16, 2016 at 17:46

2 Answers 2

5

It doesn't work because !() is an extended matching pattern, and needs to be enabled explicitly:

subprocess.run(['/bin/bash', '-O', 'extglob', '-c', 'rm -f !(INCAR|KPOINTS|PO*|*.sh)'])

Note this will remove the script itself...

Sign up to request clarification or add additional context in comments.

Comments

1

you can also use

import os
os.system('rm -f !(INCAR|KPOINTS|PO*|*.sh)')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.