Topic: Exception handling issue

I m new to python, my question is related to the exception in python
#!/usr/bin/python
import subprocess as sp
try:
p = sp.Popen(["ifconfig","eth1"],stdout=sp.PIPE)
result=p.communicate()[0]
ip=result.find("inet addr:")
start_of_ip=ip+10
end_of_ip=start_of_ip+12
ipaddr = result[start_of_ip:end_of_ip]
# print ipaddr
except:
print "error"

This is my code, here in my system there is no eth1 interface, i want that the except should handle the error and print error......
but it keep sending me the "eth1: error fetching interface information: Device not found"
can you tell me from which exception type i could handle this one.....

Thanks ..

Thumbs up

Re: Exception handling issue

>>> import subprocess
>>> p = subprocess.Popen('ifconfig eth1'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> res = p.communicate()
>>> print(p.returncode)
1
>>> res
(b'', b'eth1: error fetching interface information: Device not found\n')
>>>
>>> p = subprocess.Popen('ifconfig eth0'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> res = p.communicate()
>>> print(p.returncode)
0
>>>

if you want exception, check the return code like in the above example and raise it

Last edited by struct.h (December 21, 2011 06:00)

Thumbs up