5

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'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crappy) since I can't figure out how to get the quotes to work with subprocess.Popen. The inner single quotes must be maintained in the string variables that are passed in.

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

3 Answers 3

8

You don't need to escape the values. To the process everything is passed as a string.

You can use the shlex module to figure out what is the best way to pass variables:

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']
Sign up to request clarification or add additional context in comments.

2 Comments

This is the preferred OneWayToDoIt(tm).
Note that this doesn't work for Windows environments as shlex is meant for Unix shells.
4

You should be able to launch your script with subprocess.Popen even with quoted parameters :

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

Comments

0

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 could use this in myfile.py to check that what you get from bash is the same as what you get from subprocess.Popen (in my case it matches):

import sys
print sys.argv

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.