Search code examples
pythonlinuxpexpect

Using pexpect to remove several files from a directory in a Linux terminal


I would like to remove several files with similar names from the directory my python code is in. Doing this manually from the terminal is very simple:

rm file.*

However I understand the wildcard character is not available for use in pexpect. Since there are just four files, I was just going to spawn a child and from this child remove the desired files:

child = pexpect('rm file.1')
child.sendline('rm file.2')
child.sendline('rm file.3')
child.sendline('rm file.4')

The problem here is that the child subprocess terminates itself after spawning and removing the first file. I assume this is because the terminal returns a new line after removing a file.

So my fix is to spawn 4 children to remove the files. Like this:

child1 = pexpect('rm file.1')
child2 = pexpect('rm file.2')
child3 = pexpect('rm file.3')
child4 = pexpect('rm file.4')

Is there a better way to do this? As in more elegant and using just one subprocess? Perhaps I can keep the child alive with some sort of expectation or submit all the arguments at once in a list format?


Solution

  • WARNING: Test code that could destroy your data! Maybe you were unclear about something, or I misunderstood. Be careful!


    This should do it:

    import glob
    import os
    
    for filepath in glob.glob('file.*'):
        os.remove(filepath)
    

    Much better to use os.remove() than to call out to a subprocess.

    This exact code requires that you run it in the directory that the file.* files are in. It's easily modifiable.