I want to put this code in a Def/Main structure.
Can anybody assist me ?
from netmiko import Netmiko
with open('addresses.txt') as f1:
file1 =f1.read().splitlines()
with open('commands.txt') as f2:
file2 =f2.read().splitlines()
for ip in file1:
device = {'device_type':'cisco_ios',
'ip':ip,
'username':'user1',
'password':'secret1'
}
with open(ip + '_output.txt', 'a') as file3:
ssh = Netmiko(**device)
for cmd in file2:
output = ssh.send_command(cmd)
print(output)
print(output, file=file3)
def session1()
if __name__ == "__main__":
session1()
Iām asking if there are guidelines or best practices of where python components belong in the def/if-main structure.
Components such as: classes, methods, functions, objects, with/open/as, for/in, if/else.
In the above code, I tried some combinations putting the open/as within the def and within the if/main. I tried the same with the for/in⦠all worked fineā¦
So, Iām wondering if there are best practices for it.
In the first place, you donāt even need an āif name is mainā structure unless this is simultaneously a script and a module for other programs to use. Otherwise, just donāt bother. For the vast majority of Python programs, this simply isnāt a consideration.
But even if you do, it depends on the program itself as to what goes in there. Some put all the main code into def main(): and then just have if __name__ == '__main__': main() at the bottom; others pass sys.argv to the main function so that external callers can change the args; still others do all of the argument parsing at top-level and then call individual functions for actual tasks, which is usually best for testing, but not as easy if you need to replicate its behaviour elsewhere.
Thereās no single ābest practiceā here. Do whateverās right for your program, and donāt feel like you have to follow other peopleās guidelines.
Sounds good! Python is GREAT at letting you do simple things without boilerplate. A typical Java app requires two levels of indentation before you can even begin to write code; Python just starts you straight off with your code.