Testing functions via command line

pelon pelonpelon at gmail.com
Tue Apr 3 07:32:26 CEST 2007


There must be a couple of lines that will replace the following:

>From the shell command line I wanted to send data to a specific
function inside my module and execute that function in order to test
it separately from the rest of the module. I know pdb will allow me to
insert data into a running process, but this particular function
requires several long steps beforehand.

My command line:

myprog.py --test removefromcue "myargs"         ### removefromcue is
my function inside myprog.py


main()
...
	try:
	    opts, args = getopt.getopt(sys.argv[1:], "t:", ["--test="])
	except getopt.GetoptError:
	    for o, a in opts:
	        if o in "-t":
	            myfunc = a
		    myargs = args
		    test(myfunc, myargs)
		    sys.exit()


My problem was that I send a string into the the test function. I
needed to convert that string into the appropriate object. globals()
provides a dictionary with string:object pairs in the global
namespace.

def test(myfunc, myargs):
    """ execute a given function """
    for key,value in globals().items():
        if myfunc in key:
            func = value
            break
    args = ""
    for i in myargs:
        args += i + ","
    func(args[:-1])       ###  removefromcue("myitem")

There's something very basic that I should know.




More information about the Python-list mailing list