Easy way to store stdout to a variable?

Jp Calderone exarkun at intarweb.us
Mon Mar 10 01:22:09 EST 2003


On Sun, Mar 09, 2003 at 08:41:45PM -0800, mike wrote:
> Hi,
> 
> I am a python newbie and am trying to migrate my simple shell-script
> tasks to python.  When writing shell scripts, I make common use of
> unix pipes and filters, e.g. "ls *.txt | grep -v old | wc -l".
> 
> I know I can use "os.system()" to invoke system calls, but I don't
> know how to store the stdout of the system call into a python
> variable.
> 
> I realize I could do all of my filtering in python, but who wants to
> rewrite grep and the hundred other unix tools?
> 
> So what is an easy one-liner way to store stdout of a sytem-call to a
> variable?

    output = os.popen('command').read()

  BTW

    import glob, re, fileinput

    i = 0
    match = re.compile('old')
    for line in fileinput.FileInput(glob.glob('*.txt')):
        if not re.match(line):
            i += 1
    print i

  Much of the functionality has already been implemented for you, just need
to know where to look ;)

  Jp

-- 
Seduced, shaggy Samson snored.
She scissored short.  Sorely shorn,
Soon shackled slave, Samson sighed,
Silently scheming,
Sightlessly seeking
Some savage, spectacular suicide.
                -- Stanislaw Lem, "Cyberiad"
-- 
 up 6 days, 21:59, 10 users, load average: 0.08, 0.16, 0.13





More information about the Python-list mailing list