0

I have the following script that is used to log into Cisco devices and make config changes. The script seems ok except for the very end where the IDE complains that the "continue is not properly in loop". I want this script to be able to continue if it hits an exception. I am hitting a road block.

Thanks!

from getpass import getpass
from netmiko import ConnectHandler
import time
import sys
import traceback

username = input('Username:')
password = getpass()


with open('commands_file') as f:
    commands_list = f.read().splitlines()

with open('device_file') as f:
    devices_list = f.read().splitlines()


with open("exception_log.txt", "w") as log:

    for devices in devices_list:
        print ('Connecting to device ' + devices)
        device_ip = devices
        ios_device = {
            'device_type': 'cisco_ios',
            'ip': device_ip,
            'username': username,
            'password': password
        }

    try:
        net_connect = ConnectHandler(**ios_device)
        net_connect.save_config()
        time.sleep(5)
        output = net_connect.send_command_timing("reload in 10")
        if 'Proceed with reload?' in output:
            output += net_connect.send_command_timing("y")
        print(output)
        output = net_connect.send_config_set(commands_list)
        print(output)
        time.sleep(15)
    except:
        print("An Exception Occurred")
        traceback.print_exc(file=log)
        time.sleep(15)
        continue
ccsmooth
  • 37
  • 3
  • 1
    Your `try:` and `except:` should be inside the `for loop` – Jamiu S. Aug 08 '22 at 17:37
  • 1
    Often errors are very self explanatory. The IDE is complaining that "continue is not properly in loop" because the `continue` statement is not in your loop... Try indenting everything from `try:` – Mouse Aug 08 '22 at 17:38

2 Answers2

2

Looks like an indentation error to me, try indenting everything starting from try:, because it seems the try-except blocks are not within the loop.

MMZK1526
  • 654
  • 2
  • 16
1

You need to indent everything starting from the try, but continue has no use here, even if it was indented into the for loop.

continue skips the rest of the code in a loop and goes to the next iteration, as can be seen here:

>>> for i in range(10):
...     if i % 2 == 0:
...         continue # skips the print if i is even
...     print(i)
...
1
3
5
7
9

If you use it at the end of a for loop, it has no use as there is no code to skip over.

In the question, you said:

I want this script to be able to continue if it hits an exception

That's exactly what the try/except statement is for! It doesn't stop the program. You don't need something like continue!

The Thonnu
  • 3,578
  • 2
  • 8
  • 30