Skip to content
Advertisement

Curly braces in os.system on python

In the linux terminal i can delete all files from directory including hidden ones with:

sudo rm -rf /path/to/folder/{*,.*} 2> /dev/null

I’m trying to run the following command via os.system in python:

>>> os.system('sudo rm -rf /path/to/folder/{*,.*}')

this will exit without any error (exit code 0) but do not delete nothing.

I understand here probably the curly braces have a special meaning but trying {*,.*} will not change nothing.

Wondering what going one here and how to tell python to use the Curly braces as in the terminal.

Of corse to make the job done i can do:

os.system('sudo rm -r /path/to/folder/* /path/to/folder/.myHiddenFile')  # or other combination

But i want to understand how to play with the Curly braces here.

Advertisement

Answer

os.system calls the C standard library function system, which executes the command with /bin/sh -c.

Since the curly brace expansion you are using is a bash feature, the underlying shell that os.system is using simply does not understand.

To workaround, you can explicitly execute the command in bash by invoking /bin/bash (or whereever your bash is) with the -c argument. E.g.

os.system("/bin/bash -c 'sudo rm -rf /path/to/folder/{*,.*}'")

NOTE: the use of single quotes, which are needed because of sudo.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement