How do I pass a variable to os.popen?

extraspecialbitter pauldavidmena at gmail.com
Mon Oct 31 16:16:25 EDT 2011


I'm trying to write a simple Python script to print out network
interfaces (as found in the "ifconfig -a" command) and their speed
("ethtool <interface>").  The idea is to loop for each interface and
print out its speed.  os.popen seems to be the right solution for the
ifconfig command, but it doesn't seem to like me passing the interface
variable as an argument.  Code snippet is below:

============

#!/usr/bin/python

# Quick and dirty script to print out available interfaces and their
speed

# Initializations

output = " Interface: %s Speed: %s"

import os, socket, types

fp = os.popen("ifconfig -a")
dat=fp.read()
dat=dat.split('\n')
for line in dat:
    if line[10:20] == "Link encap":
       interface=line[:9]
    cmd = 'ethtool %interface'
    print cmd
    gp = os.popen(cmd)
    fat=gp.read()
    fat=fat.split('\n')

=============

I'm printing out "cmd" in an attempt to debug, and "interface" seems
to be passed as a string and not a variable.  Obviously I'm a newbie,
and I'm hoping this is a simple syntax issue.  Thanks in advance!



More information about the Python-list mailing list