From 358f591bb68c637de4292055e4c6e22990f6de63 Mon Sep 17 00:00:00 2001 From: Arber Zela Date: Mon, 26 Nov 2018 01:04:04 +0100 Subject: [PATCH] find nic_name automatically if misspecified --- hpbandster/utils.py | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/hpbandster/utils.py b/hpbandster/utils.py index e29a25d..df192ce 100644 --- a/hpbandster/utils.py +++ b/hpbandster/utils.py @@ -11,11 +11,30 @@ -def nic_name_to_host(nic_name): - """ translates the name of a network card into a valid host name""" - from netifaces import ifaddresses, AF_INET - host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] - return(host) +def nic_name_to_host(nic_name=None): + """ translates the name of a network card into a valid host name""" + from netifaces import ifaddresses, AF_INET + + def get_nic_name_from_system(): + import re + import subprocess + process = subprocess.Popen("ip route get 8.8.8.8".split(), + stdout=subprocess.PIPE) + output = process.stdout.read().decode() + s = re.search(r'dev\s*(\S+)', output) + return s.group(1) + + # if the network card name is not a valid one an ecxeption will be raised + # and the method get_nic_name_from_system will discover a valid card name + try: + host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] + # ValueError if the nic_name is no correct + # TypeError is nic_name is None + except (ValueError, TypeError) as e: + nic_name = get_nic_name_from_system() + host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] + + return(host)