Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #96120

Re: passing double quotes in subprocess

From Akira Li <4kir4.1i@gmail.com>
Subject Re: passing double quotes in subprocess
Date 2015-09-08 14:15 +0300
References <1e6570d1-42be-432d-a690-43c4e417ec00@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.215.1441711041.8327.python-list@python.org> (permalink)

Show all headers | View raw


loial <jldunn2000@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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

passing double quotes in subprocess loial <jldunn2000@gmail.com> - 2015-09-08 04:03 -0700
  Re: passing double quotes in subprocess Larry Martell <larry.martell@gmail.com> - 2015-09-08 07:11 -0400
  Re: passing double quotes in subprocess Chris Angelico <rosuav@gmail.com> - 2015-09-08 21:13 +1000
  Re: passing double quotes in subprocess loial <jldunn2000@gmail.com> - 2015-09-08 04:13 -0700
  Re: passing double quotes in subprocess Akira Li <4kir4.1i@gmail.com> - 2015-09-08 14:15 +0300

csiph-web