I am trying to parse a string rep of a NamedTuple for connection parameters generated remotely by the psutil library (process.connections())
The string looks like this:
pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip=\'192.168.10.26\', port=23368), raddr=addr(ip=\'1.2.3.4\', port=8883), status=\'ESTABLISHED\')
Problem is that if I declare the NamedTuple and then use eval to build it it is unable to parse the string.
Here is some sample code:
from collections import namedtuple
from socket import AddressFamily, SocketKind
inputstr = 'pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip=\'192.168.10.26\', port=23368), raddr=addr(ip=\'1.2.3.4\', port=8883), status=\'ESTABLISHED\')'
simplifiedstr = 'pconn(fd=-1, family=2, type=3, laddr=addr(ip=\'192.168.10.26\', port=23368), raddr=addr(ip=\'1.2.3.4\', port=8883), status=\'ESTABLISHED\')'
pconn = namedtuple('pconn', 'fd family type laddr raddr status')
addr = namedtuple('addr', 'ip port')
# Simplified works
conn1 = eval (simplifiedstr)
print(conn1)
# input does not
conn2 = eval( inputstr)
print(conn2)
Since simplified works, it appears that eval does not like the family and type complex values( which I don't care about anyway!)
Is there a way to make this work?
All I really need is the local address and port (in this case 192.168.10.26, 8883
)