2021年4月27日星期二

How do I reuse the code from this function cleanly?

The following function is used within a module to query network devices and is called from multiple scripts I use. The arguments it takes are a nested dictionary (the device IP and creds etc) and a string (the command to run on the device):

def query_devices(hosts, cmd):            results = {          'success' : [],          'failed' : [],      }        for host in hosts:          device = hosts[host]          try:              swp = ConnectHandler(device_type=device['dev_type'],                                   ip=device['ip'],                                   username=device['user'],                                   password=device['pwd'],                                   secret=device['secret'])              swp.enable()              results[host] = swp.send_command(cmd)              results['success'].append(host)              swp.disconnect()          except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:              results['failed'].append(host)              results[host] = e        return results  

I want to reuse all of the code to update a device and the only changes would be:

  1. The function would take the same dictionary but the cmd argument would now be a list of commands.

  2. The following line:

    results[host] = swp.send_command(cmd)  

    would be replaced by:

    results[host] = swp.send_config_set(cmd)  

I could obviously just replicate the function making those two changes and as it is in a module I reuse, I am only having to do it once but I am still basically repeating a lot of the same code.

Is there a better way to do this as I seem to come across the same issue quite often in my code.

https://stackoverflow.com/questions/67290299/how-do-i-reuse-the-code-from-this-function-cleanly April 28, 2021 at 04:34AM

没有评论:

发表评论