Running a specific funciton from command line

335
March 26, 2017, at 1:08 PM

First, I apologize, I am very new to python and programming in general. I have a python script called test.py that has three different functions within it.

def greetings():
    print "Hello User"
def salutations():
    print "Nice to meet you!"
def goodbye():
    print "Have a pleasant day"

Now what I really want to do is run the script with an argument and call the correct function based on that function like this:

python test.py greetings

In this example I would want it to run the greetings function. I've tried messing around with sys.argv but everything I've tried falls short. If anyone can help me I'd greatly appreciate it.

Answer 1

You can access command arguments via sys.argv, then get corresponding function from locals(), and call it using ().

import sys
def greetings():
    print("Hello User")
def salutations():
    print ("Nice to meet you!")
def goodbye():
    print("Have a pleasant day")
if __name__ == '__main__':
    func = sys.argv[1]
    locals()[func]()
Rent Charter Buses Company
READ ALSO
Remove cards from deck python black jack [on hold]

Remove cards from deck python black jack [on hold]

Hi I am trying to remove the cards that I bet from my 52 cards in the deck however it is not removing

551
Python - print depending on two variables

Python - print depending on two variables

so I am learning python with dataquestio

325
Python: Creating a dictionary from a file

Python: Creating a dictionary from a file

I want to write a function that opens a file containing two lines, and creates a dictionaryThe first line is the string giving the keys and the second line is the string giving the values

426
IBM Object Storage with Python

IBM Object Storage with Python

I have some issue trying to save a file to IBM object storage via pythonI copied the following credentials from the bluemix account (with details omitted below)

536