我是一名网络工程师,试图手工编写Cisco Event Manager小程序脚本是一件非常麻烦的事情,所以我拼凑了一个脚本,试图让它更容易/自动化
计划原因:
当您使用该程序时,它会将脚本输出到终端,并为您的记录创建一个文件。我创建了一个初始提示,询问您以前是否使用过该程序,以便它在开始之前完全擦除该文件。这样做的原因是为了消除数据混淆的任何可能性,并消除可能导致您尝试进行的配置更改出现问题的可能性
问题:
如果用户对最初的提示说“是”,询问他们以前是否使用过该程序,而Python无法找到该文件,则会出错
所需援助:
如果找不到文件,我想尝试让程序继续,而不是中止
(如果有人有任何关于清理的建议,也会很有帮助)
脚本:
# 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
我知道如果您的文件不存在并且用户键入“y”,就会出现问题。在这种情况下,您的函数应该如下所示:
如您所见,我添加了
os.path.exists("EMA_Script.txt")
,这将帮助您了解该文件是否存在,如果存在,则将其删除。如果文件不存在,它将继续执行下一条指令beg += 1
,从而从循环中中断让我知道这是否对你有效
open
的默认行为是在文件不存在时引发异常。如果要执行其他操作,则需要捕获异常:尽管我们在这里,但在处理文件时使用上下文是一种很好的做法,以确保它们始终处于关闭状态——事实上,任何需要关闭的文件(如数据库连接)都应该这样做。原因是,即使在
open
和close
之间发生异常,上下文也会确保文件已关闭因此,与此模式不同:
您要执行以下操作:
您可以使用try/except block捕捉
FileNotFoundError
。此外,使用break
而不是beg
变量将清理代码:第二个(嵌套的)循环也是如此:如果输入正确,则中断循环,否则继续循环
相关问题 更多 >
编程相关推荐