chorlton2080
Posts: 126
Joined: Sun Dec 23, 2012 9:44 pm

Unable to extract indexed data using split_data_index

Sun May 17, 2020 10:51 am

Hello

Following a system call to return data, I have placed the string into an index, thus:

Code: Select all

p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
I know this has worked, because on debugging the index appears in a variable:

Code: Select all

b'default', b'via', b'192.168.1.1', b'dev', b'wlan0', b'proto', b'dhcp', b'src', b'192.168.1.14', b'metric', b'303', b'192.168.1.0/24', b'dev', b'wlan0', b'proto', b'dhcp', b'scope', b'link', b'src', b'192.168.1.14', b'metric', b'303']
My need is to extract the IP address of the Pi, which is the indexed value after "src". To do this, I initiate a:

Code: Select all

ipaddr = split_data[split_data.index('src')+1]
To which I'm told "src" is not in the list, when it clearly is:

Code: Select all

Traceback (most recent call last):
  File "/home/pi/scripts/startup_mailer.py", line 26, in <module>
    ipaddr = split_data[split_data.index('src')+1]
ValueError: 'src' is not in list
Any ideas what I'm doing wrong? This script used to work.

hippy
Posts: 8924
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Unable to extract indexed data using split_data_index

Sun May 17, 2020 11:46 am

Probably comes down to the version of Python you are using ...

Code: Select all

lst = [ b'abc', b'src', b'xyz' ]
print(lst.index('src'))
print(lst[lst.index('src')+1])

Code: Select all

pi@Pi3B:~/tmp $ python2 lst.py
1
xyz

Code: Select all

pi@Pi3B:~/tmp $ python3 lst.py
Traceback (most recent call last):
  File "lst.py", line 2, in <module>
    print(lst.index('src'))
ValueError: 'src' is not in list
Using split_data.index(b'src') should resolve the issue.

chorlton2080
Posts: 126
Joined: Sun Dec 23, 2012 9:44 pm

Re: Unable to extract indexed data using split_data_index

Sun May 17, 2020 2:33 pm

Thank you. I'm still stuck in my Python 2.7 ways, and hadn't noticed Thonny was defaulting to Python 3.

Return to “Python”