我在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'))
答案 0 :(得分:1)
只需将重复的代码移出try-except子句即可:
try:
device = ...
except:
device = ...
print(device.find_prompt())
print(device.send_command('wr mem'))
print('#' * 80, '\n')