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

Suppose you have a program with several specific functions. Each function is called in a separate loop. Is it possible to indicate which function should be called via the command line?

Example:

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

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

Thanks, Seafoid.

+3
source share
5 answers

You need a module sys.

For instance:

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])

Runs a(filename)if you runpython file.py -a filename

+8
source

Python idiom for main entry point:

if __name__ == '__main__':
    main()

main() , ... ( if name ...: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm)

, , . http://docs.python.org/library/optparse.html, .

:

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

getattr.

, , "" globals ( ):

$ 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]]()

...

$ python 1933407.py second
2 of 9
+10

, -c:

python -c 'import myfile; myfile.somefunc()'
+4

:

import sys

x_is_set=False
for arg in sys.argv[1:]:
    if arg == '-x':   x_is_set=True

if x_is_set:
    print "-x is set"
+1
source

Yes, the built-in functions "exec ()" and "eval ()" are your friends. Just add '()' to the function name. However, you have to wonder if this is the best solution for a real problem. The fact that this is technically possible does not mean that it is also the best solution. The use of "exec ()" and "eval ()" is usually considered "avoidable."

0
source

Source: https://habr.com/ru/post/1726134/


All Articles