The following code in file script.py
makes it possible (after chmod 755 script.py
) to either script.py dothis
or to script.py dothat
.
import sys
def dothis():
print "We're doing this."
def dothat():
print "We're doing that."
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Error: You must specify exactly one function: dothis or dothat"
sys.exit(1)
if sys.argv[1] == "dothis":
dothis()
elif sys.argv[1] == "dothat":
dothat()
else:
print "I don't know how to "+sys.argv[1]
Is this the most elegant way to call one of two functions from the command line?