I'm new to the python programming language and I encountered a problem while doing something (apparently not) fairly simple. This is the code :
# Get the list of available network interfaces
listNIC = os.system("ifconfig -s | awk '{print 1ドル}'")
listNIC.split('\r?\n')
# Get the name of the wireless network card with iwconfig
wlanNIC = ''
i = 0
while i < len(listNIC) :
if listNIC[i].match('eth[0-9]{1}') :
wlanNIC = listNIC[i]
break
i += 1
First error comes at line 3, because for some odd reason listNIC is of type int. The error is :
Traceback (most recent call last):
File "Kol.py", line 9, in <module>
listNIC.split('\r?\n')
AttributeError: 'int' object has no attribute 'split'
I solved it by changing :
listNIC = os.system("ifconfig -s | awk '{print 1ドル}'")
into
listNIC = str(os.system("ifconfig -s | awk '{print 1ドル}'"))
But now I get an even stranger problem. I get an error that says that a string doesn't have an attribute match. Here's the error :
Traceback (most recent call last):
File "Kol.py", line 15, in <module>
if listNIC[i].match('eth[0-9]{1}') :
AttributeError: 'str' object has no attribute 'match'
So my question is the following :
- How to solve the AttributeErrors and where do they come from ?
Thanks in advance !
1 Answer 1
os.system returns the exit code of the command, not its output. You turn this number into a string, but this will not do what you want it to do. It is also deprecated. You might want to look at the subprocess module.
output = subprocess.check_output('command', shell=True)
Furthermore, you need to match using the module re. Check its documentation for the precise syntax, but it should look something like re.match(your_pattern, yourstring).
Finally, although your version is not wrong, it is more common to loop through a list like in the sample below. It is slightly shorter and more readable as you save a variable and a call to len. It is also considered more pythonic.
for nic in listNIC:
if re.match(pattern, nic):
wlanNIC = nic
break
os.system("ifconfig -s | awk '{print 1ドル}'")? I guess this returns an integer (exit value) and not the output of the command.match? That's an attribute of a regex object, not a string.