Passing an argument into Python

Up until now, I’ve been reading a file of a list of devices to log into and do some work on. That’s ideal when I have a load of routers to check, but sometimes I’d like to check one router quickly directly.

Using my OSPF Checker as an example,I currently iterate through a list of lines in devices.txt that the app then logs into. I can instead make it so that if an argument is passed in, that becomes the list and the file is ignored. If no argument is passed, I can read in the original list of devices.

To demonstrate, I’ll set up a really simple script:

#!/usr/bin/python3
import sys
print("You have passed in",sys.argv)

If I run this now form the cli I get the following:

[email protected]:~/git/ospf_checker$ ./arg.py
You have passed in ['./arg.py']

There is only a single argument, as the script itself counts itself as arg location 0. If I pass in an argument:

[email protected]:~/git/ospf_checker$ ./arg.py test
You have passed in ['./arg.py', 'test']

Most of the time I want to do some work on what’s been added after the script name. We can just be sure to look at that:

#!/usr/bin/python3
import sys
print("You have passed in",sys.argv[1])

Now when run:

[email protected]:~/git/ospf_checker$ ./arg.py test
You have passed in test

If I run the script without any arguments, I’ll get a traceback as I’m referencing an index value that doesn’t exist:

[email protected]:~/git/ospf_checker$ ./arg.py
Traceback (most recent call last):
  File "./arg.py", line 3, in 
    print("You have passed in",sys.argv[1])
IndexError: list index out of range

I can use this indexerror to do something else if no argument exists:

#!/usr/bin/python3
import sys
try:
    print("You have passed in",sys.argv[1])
except IndexError:
    print("No argument was passed, I'll do something else")
[email protected]:~/git/ospf_checker$ ./arg.py test
You have passed in test

[email protected]:~/git/ospf_checker$ ./arg.py
No argument was passed, I'll do something else

Very handy.

I’ve just scratched the surface of arguments so I’ll do a more in depth post sometime in the future

© 2009-2020 Darren O'Connor All Rights Reserved -- Copyright notice by Blog Copyright