passing double quotes in subprocess

Akira Li 4kir4.1i at gmail.com
Tue Sep 8 07:15:55 EDT 2015


loial <jldunn2000 at gmail.com> writes:

> I need to execute an external shell script via subprocess on Linux.
>
> One of the parameters needs to be passed inside double quotes 
>
> But the double quotes do not appear to be passed to the script
>
> I am using :
>
> myscript = '/home/john/myscript'
> commandline = myscript + ' ' + '\"Hello\"'
>
> process = subprocess.Popen(commandline, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> output,err = process.communicate()
>
>
> if I make the call from another shell script and escape the double
> quotes it works fine, but not when I use python and subprocess.
>
> I have googled this but cannot find a solution...is there one?

You don't need shell=True here:

  #!/usr/bin/env python3
  from subprocess import Popen, PIPE

  cmd = ['/home/john/myscript', 'Hello'] # if myscript don't need quotes
  # cmd = ['/home/john/myscript', '"Hello"'] # if myscript does need quotes
  with Popen(cmd, stdout=PIPE, stderr=PIPE) as process:
     output, errors = process.communicate()

In general, to preserve backslashes, use raw-string literals:

  >>> print('\"')
  "
  >>> print(r'\"')
  \"
  >>> print('\\"')
  \"


  >>> '\"' == '"'
  True 
  >>> r'\"' == '\\"'
  True




More information about the Python-list mailing list