Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

Capturing output of os.system to a string

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


gabutler at acslink

Nov 23, 2009, 5:27 PM

Post #1 of 4 (566 views)
Permalink
Capturing output of os.system to a string

How do I capture output to a string? For example, the output of
os.system('whoami').

I guess I need to redirect stdout, but I'm a total beginner, and I
haven't been able to find out from the tutorials how to do this.

--
http://mail.python.org/mailman/listinfo/python-list


apt.shansen at gmail

Nov 23, 2009, 5:36 PM

Post #2 of 4 (569 views)
Permalink
Re: Capturing output of os.system to a string [In reply to]

On Mon, Nov 23, 2009 at 5:27 PM, gerry.butler <gabutler [at] acslink>wrote:

> How do I capture output to a string? For example, the output of
> os.system('whoami').
>
> I guess I need to redirect stdout, but I'm a total beginner, and I
> haven't been able to find out from the tutorials how to do this.
>
>
You don't; os.system is only usable to send commands off that need no input
and which you don't care for the output. Check out the subprocess module.

You can do like:

popen = subprocess.Popen("whoami", stdout=subprocess.PIPE)

Then "out, err = popen.communicate()"

The 'out' should contain the output from the command.

--S


lie.1296 at gmail

Nov 23, 2009, 5:40 PM

Post #3 of 4 (566 views)
Permalink
Re: Capturing output of os.system to a string [In reply to]

gerry.butler wrote:
> How do I capture output to a string? For example, the output of
> os.system('whoami').
>
> I guess I need to redirect stdout, but I'm a total beginner, and I
> haven't been able to find out from the tutorials how to do this.
>

You can't with os.system; use subprocess module instead.
--
http://mail.python.org/mailman/listinfo/python-list


gabutler at acslink

Nov 23, 2009, 6:11 PM

Post #4 of 4 (556 views)
Permalink
Re: Capturing output of os.system to a string [In reply to]

Thank you. I'll look at subprocess.

I have since found that commands will do it too, eg,

(status, txt) = commands.getstatusoutput('whoami')

or txt = commands.getoutput('whoami')



--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.