[Tutor] Subprocess how to use?

Cameron Simpson cs at zip.com.au
Fri Nov 7 06:23:18 CET 2014

On 06Nov2014 22:18, jarod_v6 at libero.it <jarod_v6 at libero.it> wrote:
>Dear All thanks  so much for the suggestion !!!
>One thing is not clear to me: How can write more safe string to send on
>subprocess.Popen() without %s? What is the best way to do this?

The safest way is to use shell=False and pass a python list with the command 
line strings in it.

If you absolutely must generate a shell command string, you need to use some 
intermediate function that knows how to quote a string for the shell. Eg:

  def shell_quote(s):
    return "'" + s.replace("'", r"'\''") + "'"

That's untested, but it puts a string in single quotes and correctly escapes 
any single quotes in the string itself. Then you'd go:

  shcmd = "cat %s %s" % (shell_quote(filename1), shell_quote(filename2))
  P = Popen(shcmd, shell=True)

You will see the same kind of thing in most database interfaces, but presented 
more conveniently. As with the shell, it is always bad to go:

  sqlcmd = "INSERT into Table1 values(%s,%s)" % (value1, value2)

because value1 or value2 might have SQL punctuation in it. Eg:


Instead you will usually use a call like this:

  db_handle.execute("INSERT into Table1 values(?,?)", value1, value2)

and the .execute function will itself call the right SQL quoting function and 
replace the "?" for you.

Cameron Simpson <cs at zip.com.au>

... It beeped and said "Countdown initiated." Is that bad?

More information about the Tutor mailing list