0

I would like to get the first interface that is up on a linux machine. I am using subproces and I have the following piece of code :

def get_eth_iface():
    awk_sort = subprocess.Popen( ["-c", "ifconfig | cut -d ' ' -f 1 | grep eth | head -n 1" ], stdin= subprocess.PIPE, shell=True )
    awk_sort.wait()
    output = awk_sort.communicate()[0]

But with this result will be printed to the console and won't be saved to the variable. How can I redirect this to the variable ?

2 Answers 2

1

Redirect the stdout to subprocess.PIPE. Following works for me.

import subprocess
def get_eth_iface():
    awk_sort = subprocess.Popen( ["dir" ], stdin= subprocess.PIPE, stdout= subprocess.PIPE)
    awk_sort.wait()
    output = awk_sort.communicate()[0]
    print output.rstrip()
get_eth_iface()
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, thanks that works good BUT : I have to do that output = awk_sort.communicate()[0]to get the actual interface name + I get the interface name with new line sign. How can I get rid of that ?
Just use the rstrip method on strings.
1

http://docs.python.org/2/library/subprocess.html:

Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Sounds like a good advice. Add stdout=subprocess.PIPE and see what happens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.