Python subprocess module

I need to run this command using python subprocess module (notice I'm using only variables):

cmd = TESTPATH + ' -s ' + serviceName + ' -r ' + rdir + \
          ' -m ' + masterAcct + ' -p ' + persona + ' -P ' + passwd

Can you give a more concrete command/example?
To use subprocess, maybe you can take a look the codes below, I used

grep -E -A1 -B1 sys /etc/passwd

as command. it print out the line containing "sys" in my /etc/passwd, also 1 line before and after the matched lines are also printed.

kent$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess, shlex
>>> cmd="grep -E -A1 -B1 sys /etc/passwd"
>>> args=shlex.split(cmd)
>>> subprocess.Popen(args)
<subprocess.Popen object at 0xb753220c>
>>> bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
--
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:102::/home/syslog:/bin/false
klog:x:102:103::/home/klog:/bin/false
hplip:x:103:7:HPLIP system user,,,:/var/run/hplip:/bin/false
avahi-autoipd:x:104:110:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/bin/false

TESTPATH as the name implies is a string containing a path to a binary, it's not a unix command (I wrote it), serviceName,rdir,masterAcct,persona,passwd are variables (strings) like:
rdir = 'hostname.con'
masterAcct = 'guy01'
and so on...

I just managed to get it working like this:

subprocess.Popen([TESTPAHT, '-s', serviceName, '-r', rdir, '-m', masterAcct, '-p', persona, '-P', passwd])

Please advice, should I use SHELL=true or false?

i think shell should be false, if the command ("binary") is in the 1st element of the list. I have ever used a self-written C program as command, it worked. But if you want to run the command in a particular shell, you should set shell=true, and set executable option.

following texts are taken from python doc.

1 Like