[Wolves] Another python question, running commands with variables as arguments.

Alex Willmer alex at moreati.org.uk
Thu Aug 18 22:41:04 UTC 2011


On 18 August 2011 10:47, Simon Burke <simonb at fatsportsman.eu> wrote:
> An example of the code I'm trying to use is: (the code currently just
> prints out the command).
>
>                        for filesys in bp1_fs:
>                                print "mount %s:/vol/%s  -t nfs -o %s"
> % (nas1, filesys, moptions)
>                        for ipaddr in bp1_ip:
>                                print "ip addr add %s dev %s" % (ipaddr, int)
>                        print "su - %s -c startdb" % (bp1_usr)
>                        for inst in bp1_inst:
>                                print "su - %s -c startsap %s" % (bp1_usr, inst)

If you want to read the output of each command try this
for filesys in bp1_fs:
    p = subprocess.Popen(["mount", "%s:/vol/%s" % (nas1, filesys),
                                   "-t", "nfs",
                                   "-o", moptions])
    stdout, stderr = p.communicate()
    for ipaddr in bp1_ip:
        p = subprocess.Popen(["ip", "addr", "add", ipaddr, "dev", int]) # NB
        stdout, stderr = p.communicate()
    p = Popen(["su", "-", bp1_usr, "-c", "startdb"])
    stdout, stderr = p.communicate()
    for inst in bp1_inst:
        p = subprocess.Popen(["su", "-", bp1_usr, "-c", "startsap", inst])
        stdout, stderr = p.communicate()

A few notes:
 - In Python [x, y, z] defines a list, not an array.
 - On the line I've marked NB your code used int as a variable name.
int is the builtin integer type, using it as a variable name will
cause errors.
 - If you want the return value of the command once it has completed,
it will be p.returncode
 - If your any of your arguments are wildcards then specify shell=True
e.g. p = subprocess.Popen(["ls", "/*"], shell=True)

HTH, Alex
P.S. Python West Midlands are running a conference in September, be
great if you could come http://www.pyconuk.org
P.P.S If you haven't already, please join PyWM http://pywm.eu/
-- 
Alex Willmer <alex at moreati.org.uk>
http://twitter.com/moreati



More information about the Wolves mailing list