Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - specify which function in file to use on command line

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.

like image 859
Darren J. Fitzpatrick Avatar asked Nov 29 '22 11:11

Darren J. Fitzpatrick


2 Answers

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.

And finally, another 'generic' approach using globals (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
like image 173
miku Avatar answered Dec 05 '22 19:12

miku


You want the sys module.

For example:

import sys

#Functions
def a(filename): pass
def b(filename): pass
def c(filename): pass

#Function chooser
func_arg = {"-a": a, "-b": b, "-c": c}

#Do it
if __name__ == "__main__":
    func_arg[sys.argv[1]](sys.argv[2])

Which runs a(filename) if you run python file.py -a filename

like image 43
me_and Avatar answered Dec 05 '22 19:12

me_and