Sheena Wadhwa Sheena Wadhwa - 1 year ago 66
Python Question

print the selected choice name as well

I am unable to place the print command for printing the name of selected choice. The code is as follows:

import dpkt
from dpkt.ip import IP
from dpkt.ethernet import Ethernet
import struct
import socket
import csv
def ip_to_str(address):
return socket.inet_ntoa(address)

whose output is as follows:

, 4, 20, 60
, 4, 20, 60
, 4, 20, 52
, 4, 20, 193
, 4, 20, 341

But I want that it should have the headers name at top like as follows, so expected output is:

Select IPv4 Header Fields:
1) Ver
2) HeaderLength
3) Total Length
4) Exit
Choose your option:'1,2,3'
, Ver, HeaderLength, Total Length
, 4, 20, 60
, 4, 20, 60
, 4, 20, 52

Any help will be appreciated.

Answer Source

Add this code after the line choice = ch.split(',')

dict = {'1':'Ver', '2':'HeaderLength', '3':'TotalLength'}
print(', '.join([dict[i] for i in choice if i in dict.keys()]))

I would recommend you replace your while loop with the following:

while loop:
    print("Select IPv4 Header Fields:")
    print ("1) Ver")
    print ("2) HeaderLength")
    print ("3) Total Length")
    print ("4) Exit")
    choice = [i.strip() for i in input("Choose your options:").split(',')]

    if not set(choice)-set(['1','2','3','4']): # check for valid choices
        print("Enter valid choices\n")

    if '4' in choice: loop = 0 # you want to break out, after executing the next loop

    for ts, buf in pcap:
        eth = dpkt.ethernet.Ethernet(buf)
        if eth.type != dpkt.ethernet.ET_TYPE_IP:
        ip =
        data = {'1':str(ip.ver), '2':str(dpkt.ip.IP_HDR_LEN), '3':str(ip.len)}

        ff = ','.join([data[i] for i in choice if i in data.keys()])
        print ff

You may also want to check whether all choices are valid or not. For example, user can enter 1,2,34,42,4 as input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download