tags:

views:

76

answers:

3

How do I pipe the output of file to a variable in Python?

Is it possible? Say to pipe the output of netstat to a variable x in Python?

+5  A: 

It is possible. See:

http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote

In Python 2.4 and above:

from subprocess import *
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]
Richard Fearn
Are you sure that works? I don't think the backticks call to the shell in Python and usage of them is discouraged anyway.
Mark Byers
Hello, figured I'd try it. The backticks are required at least using cygwin. Without backticks I get help spit back at me.>>> x = Popen(["netstat", "-a", "-b", "-e"], stdout=PIPE).communicate()[0]>>> x'Interface Statistics\r\n\r\n Received Sent\r\n\r\nBytes 636096584 44729983\r\nUnicast packets 540296 297233\r\nNon-unicast packets 1058608 338\r\nDiscards 0 0\r\nErrors 0 13\r\nUnknown protocols 4405\r\n'
manifest
Tried it in DOS also, same deal. Back-ticks required.
manifest
@manifest: backticks in Python call repr on an object - they do not make calls to the shell. When you say they are required, how are you using them? They do not appear in the example you posted.
Dave Kirby
Sorry, the command with backticks is the shell command being replaced with a subprocess call. I've updated my answer. And I should have spotted that - we have loads of code that converts to strings with backticks! Thanks for spotting it.
Richard Fearn
I thought "back-ticks" referred to the "-" before each argument. Sorry for confusion.
manifest
+1  A: 

Take a look at the subprocess module. It allows you to start new processes, interact with them, and read their output.

In particular see the section Replacing /bin/sh shell backquote:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
Mark Byers
+2  A: 

Two parts:

Shell

netstat | python read_netstat.py

Python read_netstat.py

import sys
variable = sys.stdin.read()

That will read the output from netstat into a variable.

S.Lott