How do I pass a variable to os.popen?
Chris Rebert
clp2 at rebertia.com
Mon Oct 31 16:48:02 EDT 2011
On Mon, Oct 31, 2011 at 1:16 PM, extraspecialbitter
<pauldavidmena at gmail.com> wrote:
> 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
os.popen() is somewhat deprecated. Use the subprocess module instead.
> 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'
cmd will literally contain a percent-sign and the word "interface". If
your shell happens to use % as a prefix to indicate a variable, note
that Python variables are completely separate from and not accessible
from the shell. So either ethtool will get the literal string
"%interface" as its argument, or since there is no such shell
variable, after expansion it will end up getting no arguments at all.
Perhaps you meant:
cmd = "ethtool %s" % interface
Which could be more succinctly written:
cmd = "ethtool " + interface
> print cmd
> gp = os.popen(cmd)
> fat=gp.read()
The subprocess equivalent is:
fat = subprocess.check_output(["ethtool", interface])
> 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!
Cheers,
Chris
--
http://rebertia.com
More information about the Python-list
mailing list