subprocess.popen and static define in Python

I like os’s subprocess.Popen() to run shell commands from within my Python code. It’s fine to call it directly because I usually only need one or two shell commands and can use other functions of the os module such as link() and unlink() to create or delete files. Sometimes I need a bunch of Popen’s because i’m trying to run other programs and pass them parameters. It’s a lot of code to grab all of the standard i/o. So I made a function for it…

def cmd(self, command):
    if command:
        p = subprocess.popen([command], shell=True, \
            stdin=subprocess.PIPE, \
            stdout=subprocess.PIPE, \
            stderr=subprocess.PIPE)
        return p
    else:
        return 0

It works great in a class where I can just call self.cmd(’do something’)

But I also like to define TRUE and FALSE as 1 and 0 to use as return values because it can get confusing when you mix python with bash and you think exit 0 is a good thing. Now I know what you’re thinking: there’s no such thing as ‘C’s #define in python because there’s no compiler to swap out of all your substitutions at compile time. However, it’s just as easy to achieve the same results:

class SomeClass:

    def __init__(self):
        self.TRUE = 1
        self.FALSE = 0

    def cmd(self, command):
    if command:
        p = subprocess.popen([command], shell=True, \
            stdin=subprocess.PIPE, \
            stdout=subprocess.PIPE, \
            stderr=subprocess.PIPE)
        return self.TRUE
    else:
        return self.FALSE
Posted by admica   @   13 January 2010

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
« Paid Pundit Palin!
Next Post
Python Regular Expression Syntax »
Powered by Wordpress   |   Lunated designed by ZenVerse