Home > Software design >  Presenting output of while loop as selection for user
Presenting output of while loop as selection for user

Time:06-05

Here is what I have so far

#!/usr/bin/python3
import netifaces
interfaces = [i for i in netifaces.interfaces() if not i.startswith(("lo", "ipsec", "tun"))]
count = len(interfaces)
i = 0
x = 0
  while i < len(interfaces):  
  print("Interface "   interfaces[i])  
  i  = 1  
  x  = 1

This will print a list of interfaces but I would like to present that list as something the customer can select. i.e. "Please select external interface 1.) enp1s0 2.) enp0s21f0u4 3.) wlp2s0 4.) exit

Thank you for any help you can provide

CodePudding user response:

Python relies upon indentation to block out the code, so the indentation on that while statement is a problem. You generally don't need as many counter variables as you may have to use in C. I don't know if you're using count and x later on in your code, but you're not using them here so I took them out. Without the counters you can take out that while and replace it with a for.

This has no input-validation, but try this:

#!/usr/bin/python3

import netifaces

interfaces = [i for i in netifaces.interfaces() if not i.startswith(("lo", "ipsec", "tun"))]

print("Choose an interface:")
for i in range(len(interfaces)):
    print("\t{}) ".format(i 1), interfaces[i])

sel = int(input("\n> "))-1

print("You have selected interface {}.".format(interfaces[sel]))

You mentioned that you're doing this for a customer: make sure you validate that input before converting it to an int() and using it.

CodePudding user response:

Just add this lines:

print("Please select external interface:\n 1.) enp1s0\n 2.) enp0s21f0u4\n 3.) wlp2s0\n 4.) exit\n")
value = input("")
  • Related