Putting a code in Def/Main structure

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()



You mean you want the code to be in the session1 function?

def session1():
      print(‘code goes here’)

Is the above what you are looking for?

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.

1 Like

Well, I won’t bother myself as I do straightforward stuff.

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.

1 Like