How do I pass file output to a variable in Python?

How do I pass file output to a variable in Python?

Is it possible? Say to pass the output of the netstatvariable x to Python?

+5
source share
3 answers

Two parts:

Shell

netstat | python read_netstat.py

Python read_netstat.py

import sys
variable = sys.stdin.read()

This will read the output of netstat into a variable.

+5
source

It is possible. Cm:

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

In Python 2.4 and later:

from subprocess import *
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]
+6
source

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

In particular, see Replacing / bin / sh shell backquote :

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
+2
source

All Articles