ActiveState Code

Recipe 52206: Use simple command-line options to effect program runtime.


Using sys.argv and globals(), you can build scripts which can modify their behavior at runtime based on arguments passed on the command line. This script, 'test_test.py' is built to be run from the command line. It allows you to invoke the script without any command-line arguments, in which case, the main() function is run. However, if the script is invoked via "python test_test.py debug", the debug function is run instead. This script uses Stephen Purcell's 'unittest' module from his PyUnit unit testing framework.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import unittest

class Tests(unittest.TestCase):
    def testAddOnePlusOne(self):
        assert 1 + 1 = 2, 1 + 1

def main():
   unittest.TextTestRunner().run(test_suite())

def test_suite():
   return unittest.makeSuite(Tests, 'test')

def debug():
   test_suite().debug()

if __name__=='__main__':
   if len(sys.argv) > 1:
      globals()[sys.argv[1]]()
   else:
      main()

Comments

  1. 1. At 11:30 a.m. on 8 mar 2001, Nick Mathewson said:

    An extension for arugment handling. This is cute; I hadn't seen this one before.

    If I might suggest an extension, why not change the line "globals()sys.argv[1]" to "apply(globals()[sys.argv[1]], sys.argv[2:])". This allows you to pass string arguments to your functions. Nick Mathewson

Sign in to comment