Jake
Jake

Reputation: 917

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

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?

Upvotes: 5

Views: 1206

Answers (3)

S.Lott
S.Lott

Reputation: 391862

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.

Upvotes: 5

Richard Fearn
Richard Fearn

Reputation: 25491

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]

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 838376

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]

Upvotes: 2

Related Questions