bash case statement in python

Having read PyDanny’s blog post about python’s absence of a switch/case statement and how to do it instead, I thought I give it a go and make a one-to-one comparison of something one may put into a bash script and implement the same in a simple python script.

#!/usr/bin/env bash

start() {
echo "Start application..."
}

stop() {
echo "Stop application..."
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart)
start
stop
;;
*)
echo "$0 [start|stop|restart]"
;;
esac

Lines: 24

the equivalent python script

#!/usr/bin/env python
from __future__ import print_function
import sys
def start():
print("Starting application...")
def stop():
print("Stopping application...")
def restart():
stop()
start()
def help(argv):
print("{0} [start|stop|restart]".format(argv[0]))
sys.exit(1)
switcher = {
"start": start,
"stop": stop,
"restart": restart
}
try:
arg = sys.argv[1]
switcher.get(arg, lambda: help(sys.argv))()
except IndexError:
help(sys.argv)

Lines: 29

output

$ python switch.py restart
Stopping application...
Starting application...
$ python switch.py blabla
switch.py [start|stop|restart]

conclusions

It’s relatively easy to implement a case/switch functionality in python, even if it’s a couple more lines to write (in this comparison, fwiw) and needs a slightly different approach.

You will need to use the from __future__ import print_function to make the lambda work properly.