删除try和except块中的重复项

时间:2019-10-15 23:32:55

标签: python python-3.x

我在try和except块中有重复项。如何从代码中删除重复项?

def ssh_function():
for test in xyz:
    try:
        device = ConnectHandler(ip=test, 
                                username='admin', 
                                password='admin', 
                                device_type='cisco_ios')
        print(device.find_prompt())
        print(device.send_command('wr mem'))

    except Exception:
        device = ConnectHandler(ip=test, 
                                username='admin', 
                                password='admin', 
                                device_type='cisco_ios_telnet')  #### Different from try block
        print(device.find_prompt())
        print(device.send_command('wr mem'))

1 个答案:

答案 0 :(得分:1)

只需将重复的代码移出try-except子句即可:

try:
    device = ...
except:
    device = ...

print(device.find_prompt())
print(device.send_command('wr mem'))
print('#' * 80, '\n')