Python - specify which function in file to use on command line
Question: Assume you have a programme with multiple functions defined. Each function is
called in a separate for loop. Is it possible to specify which function should
be called via the command line?

Example:

    
    
    python prog.py -x <<<filname>>>
    

Where -x tells python to go to a particular for loop and then execute the
function called in that for loop?

Thanks, Seafoid.


Answer: The Python idiom for the main entry point:

    
    
    if __name__ == '__main__':
        main()
    

Replace `main()` by whatever function should go first ... (more on `if name
...`: <http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm>)

If you want to specify the function to run via command line argument, just
check these arguments, either manually or via some helpers, e.g.
<http://docs.python.org/library/optparse.html>, then branch of to the desired
function.

If you don't want stuff like this:

    
    
    if options.function_to_call == 'mydesiredfunction':
        mydesiredfunction()
    

You can take advantage of
[`getattr`](http://diveintopython.net/power_of_introspection/getattr.html).

And finally, another 'generic' approach using
[`globals`](http://www.faqs.org/docs/diveintopython/dialect_locals.html)
(exception handling excluded):

    
    
    $ cat 1933407.py
    
    #!/usr/bin/env python
    # coding: utf-8
    
    import sys
    
    def first():
        print '1 of 9'
    
    def second():
        print '2 of 9'
    
    def seventh():
        print '7 of 9'
    
    if __name__ == '__main__':
        globals()[sys.argv[1]]()
    

Meanwhile at the command line ...

    
    
    $ python 1933407.py second
    2 of 9
    

