sunyata sunyata - 2 months ago 10
Bash Question

Escaping with backslash or quoting in the shell?

When starting a program via the command line using

os.system(program file_argument))
and where the argument is a file (which might have whitespace in it) what is the best way to send the argument to the other program?

I've looked at these options:


  • Using
    pipes.quote(file_name)
    (or
    shlex.quote(file_name)
    for Python 3) which produces a string like this:
    '/dir/file with white space'

  • Using
    re.escape(file_name)
    which produces string like this:
    /dir/file\ with\ white\ space



Are there differences between using these that might impact the program that is called? (Are there any other options?) Anything else i need to consider?

Answer
>>> import subprocess
>>> subprocess.call(['cat', 'file with space.txt'])

Using os.system, while simple to get started, breaks down when trying to do more complicated tasks.

I wish I had given up on os.system much earlier and just got familiar with subprocess. Well worth the time.