Python subprocess with arguments having multiple quotes

I use the following command in bash to execute a Python script.

python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'"

I am writing a Python script to wrap this. I currently have to use os.system (I know this is crappy), since I cannot figure out how to make quotes work with subprocess.Popen. Inner single quotes must be supported in string variables that are passed.

Can someone please help me determine how to format the first variable passed to the .Popen subprocess.

+5
source share
3 answers

You do not need to avoid values. For the process, everything is passed as a string.

shlex :

import shlex
shlex.split('python myfile.py -c "USA" -g "CA" -0 "2011-10-13" -1 "2011-10-27"') 
['python',
 'myfile.py',
 '-c',
 'USA',
 '-g',
 'CA',
 '-0',
 '2011-10-13',
 '-1',
 '2011-10-27']
+8

script subprocess.Popen :

subprocess.Popen([
   "/usr/bin/python", 
   "myfile.py",
   "-c",
   "'USA'",
   "-g",
   "'CA'",
   "-0",
   "'2011-10-13'",
   "-1",
   "'2011-10-27'",
])
+4

Have you tried this?

import subprocess
subprocess.Popen(['python', 'myfile.py', '-c', "'USA'", '-g', "'CA'", '-0', "'2011-10-13'", -1, "'2011-10-27'"]).communicate()

You can use this in myfile.pyto verify that what you get from bashmatches what you get from subprocess.Popen(in my case, it matches):

import sys
print sys.argv
0
source

All Articles