0

First after all I'm a total newbie on Python. I'm trying to make a Python file with two methods like this:

def hello():
    print("Hello.")

def bye():
    print("Bye bye.")

I know an option that works with just one method.

if __name__ == "__main__":
    hello()

This will let open the file from CMD, using this command:

>python file.py 

Again, it will open the file but deploying hello(), I need something to let the user pick hello() or bye() method. On internet I saw that the following CMD command

>python file.py hello()
>python file.py bye() 

somehow works, but I don't know how, do someone knows?

Greetings!

1 Answers1

5

You need to handle the command line arguments, which are available in sys.argv.

The most straightforward way would be:

import sys

def hello():
    print("Hello.")

def bye():
    print("Bye bye.")

def main():
    funcname = sys.argv[1]
    if funcname == 'hello':
        hello()
    elif funcname == 'bye':
        bye()
    else:
        print("ERROR: Invalid function")   

if __name__ == '__main__':
    main()

An improvement on this would be to create a mapping:

import sys

def hello():
    print("Hello.")

def bye():
    print("Bye bye.")

def main():
    funcmap = {
        'hello': hello,
        'bye':   bye,
    }
    def invalid():
        print("ERROR: Invalid function")
        sys.exit(1)

    funcname = sys.argv[1]
    f = funcmap.get(funcname, invalid)
    f()

if __name__ == '__main__':
    main()

If you want to something more complex, like the way git handles sub-commands, e.g. git push origin master and git status, then I would recommend using argparse sub-parsers. See this question/answer for more details.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328