ouput redirection..a newbie question
Lonnie Princehouse
fnord at u.washington.edu
Mon Dec 15 15:27:59 EST 2003
You can also use os.popen() to capture the output of a shell command:
import os
p = os.popen('ls -al')
output = p.read() # read output of command
print output
(a variation on this, os.popen3, can be used if you need to capture
stdout and stderr separately...)
Jp Calderone <exarkun at intarweb.us> wrote in message news:<mailman.153.1071498225.9307.python-list at python.org>...
> On Tue, Dec 18, 2001 at 03:46:26PM +0530, Gautam Pagedar wrote:
> > Hello,
> >
> > i am new to python and need a basic answer. Hope someone would help me
> > solve this.
> >
> > I want to execute a command ls -l and sore its result in a file.
> >
> > >>import sys
> > >>import os
> > >>os.system("ls -al")
> >
> > executes the command how can i redirect the to a file like we do in
> > shell script using a redirection operator.
> >
>
> This works:
>
> os.system("ls -al > foo")
>
> Perhaps more usefully, though, the "commands" module allows you to get the
> output of a program as a string:
>
> foo = commands.getoutput("ls -al")
>
> And it might be helpful to know that Python itself has functions for
> listing files:
>
> fileList = os.listdir(".")
>
> As well as for getting information about them:
>
> fileMTimes = [os.path.getmtime(f) for f in os.listdir(".")]
> filePermissions = [os.stat(f).st_mode for f in os.listdir(".")]
>
> For more information, see http://www.python.org/doc/lib/
>
> Jp
More information about the Python-list
mailing list