1

I am a network engineer and trying to write Cisco Event Manager Applet scripts by hand was a huge hassle so I pieced together a script to try and make it easier/automated-ish.

Reason For Program:

When you use the program it outputs your script to the terminal and creates a file for your records. I created an initial prompt to ask if you have ever used this program before so that it will completely erase the file before beginning. The reason for this was to remove any chance of data getting mixed up and potentially causing issues with the configuration changes you are trying to make.

Problem:

If users say "yes" to the initial prompt asking if they have used the program before and Python can't find the file it errors out.

Assistance Needed:

I want to try to have the program just continue if the file is not found rather than aborting.

(Any suggestions on cleaning this up would be helpful too if anyone has any)

Script:

# Used for creating, editing, erasing, reading files #
import os

# First While loop counter #
beg = 0
# Second While loop counter #
counter0 = 0
# Nested While loop counter #
counter1 = 0
# Used to start CLI action numbering at the correct point #
line = 3

# Searches for any previously made EMA script file and removes it. Currently errors out if file isn't seen #
while beg == 0:

    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()

    if remove == "y":
        os.remove("EMA_Script.txt")
        print("File Deleted")
        beg += 1

    elif remove == "n":
        beg += 1

    else:
        print("Incorrect input.")
        beg += 0

# Begins asking for CLI commands and writing inputs to file in sequence #
while counter0 == 0:

    name = input("\nName your applet: ")
    hour = int(input("\nAt what hour do you want this to run (24h clock)?: "))
    minute = int(input("\nAt what minute on the hour do you want this to run?: "))

    f = open("EMA_Script.txt", "a+")
    f.write('event manager applet {}\nevent time cron cron-entry "{} {} * * *"'.format(name, minute, hour))
    f.write('\naction 1.0 cli command "enable"\naction 2.0 cli command "conf t"')
    f.close()

    while counter1 == 0:
        print("\nBegin Command section.")
        action = input("\nCommand: ")
        forward = input("\nEnter 1 to add more or 2 if you are finished: ")

        if forward == "1":
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "{}"'.format(line, action))
            f.close()
            line += 1
            counter1 += 0

        elif forward == "2":
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "{}"'.format(line, action))
            f.close()
            line += 1
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "end"'.format(line))
            f.close()
            f = open('EMA_Script.txt', 'r')
            print(f.read())
            f.close()
            counter1 += 1

        else:
            print("Incorrect input. Re-input previous command!")
            counter1 += 0

    break
1
  • You can use try - except or better 'try' - with - except to suppress errors. Commented Mar 20, 2020 at 15:46

3 Answers 3

1

I understand that the problem arises if your file doesn't exist and the user type "y". In this case your function should look like this:

# Searches for any previously made EMA script file and removes it. Currently errors out if file isn't seen #
while beg == 0:

    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()

    if remove == "y":
        # This line will check if the file exists, if it does it will be deleted
        if os.path.exists("EMA_Script.txt"):
            os.remove("EMA_Script.txt")
            print("File Deleted")
        beg += 1

    elif remove == "n":
        beg += 1

    else:
        print("Incorrect input.")
        beg += 0

As you can see I added os.path.exists("EMA_Script.txt") this will help you to know if the file exists and delete it if it does. If the file doesn't exist, it will simply continue with the next instruction beg += 1 and therefore break out from the loop.

Let me know if that worked for you!

Sign up to request clarification or add additional context in comments.

1 Comment

This works and lets me output something else for when they choose "no". Thank you for this.
1

The default behaviour of open is to raise an exception if the file does not exist. You'll need to catch the exception if you want to do something else:

try:
    f = open("EMA_Script.txt", "a+")
except FileNotFoundError:
    # your code to handle the case when the file doesn't exist (maybe open with write mode)

While we're here though, it's good practice to use contexts when working with files to ensure they always get closed - in fact anything that needs to be closed like database connections should be done this way. The reason is that the context will ensure that the file is closed even if something in between the open and close raises an exception.

So instead of this pattern:

f = open(...)
# do things with file
f.close()

You want to do this:

with open(...) as f:
    # do things with file

1 Comment

This worked wonderfully! Best practices are always best to use for sure. Much appreciated
1

You can use a try/except block to catch the FileNotFoundError. Additionally, using break instead of the beg variable will clean up your code:

import os

while True:
    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()
    if remove == "y":
        try:
            os.remove("EMA_Script.txt")
            print("File Deleted")
        except FileNotFoundError:
            pass
        break
    elif remove == "n":
        break
    else:
        print("Incorrect input.")

The same goes for your second (nested) loop: Break out of the loop if the input was correct, and just keep looping otherwise.

1 Comment

This way is a correct answer and works great. Even if they say "no" it still says "File Deleted". Not a huge deal though. Thank you for the advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.