Search code examples
pythonpython-3.xargvsys

Using sys.argv to retrieve different functions


So let's say I have these lines of code:

if __name__ == '__main__':
if '-h' in sys.argv:
    show_help()
elif '-f' or 'function'in sys.argv:
    print(function1)
elif '-n'or '-name' in sys.argv:
    print(function2)
elif '-e' or '-extension'in sys.argv:
    print(function3])
elif '-m' or '-missing'in sys.argv:
    print(function4)
elif 'r' or '-range' in sys.argv:
    print(function5)
else:
    exit

The letters are supposed to be inputs from the user in the bash terminal. Showing the help method works and it is able to show all of the strings. The -f input works and shows the contents that I need in that function, however the code just spits out the content from function 1 and not from function2 and so on.

How do I get these different letters, -f, -n, -e, -m (if inputted) to carry out that function and spit out that information? Also is there a more efficient way to do this without using argparse for a beginner Python scripter?


Solution

  • I highly suggest using argparse.

    If you prefer not to, creating a dictionary of flags is also possible:

    flags = {
        '-h': show_help, 
        '-f': function1,
        '-function': function1,
        '-n': function2,
        '-name': function2,
        '-e': function3,
        '-extension': function3,
        '-m': function4,
        '-missing': function4,
        '-r': function5,
        '-range': function5,
    }
    if __name__ == '__main__':
        for flag in sys.argv:
            print(flags[flag])
    

    By creating a dictionary, you're able to just look up the keys.

    It results in cleaner, faster, and more maintainable code.