Welcome, guest | Sign In | My Account | Store | Cart

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, 20 lines
 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()

1 comment

Nick Mathewson 23 years, 1 month ago  # | flag

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

Created by Chris McDonough on Sat, 3 Mar 2001 (PSF)
Python recipes (4591)
Chris McDonough's recipes (4)

Required Modules

  • (none specified)

Other Information and Tasks