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.
You need a module sys.
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
a(filename)
python file.py -a filename
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)
main()
if name ...
, , . http://docs.python.org/library/optparse.html, .
:
if options.function_to_call == 'mydesiredfunction': mydesiredfunction()
getattr.
getattr
, , "" globals ( ):
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
, -c:
-c
python -c 'import myfile; myfile.somefunc()'
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"
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."
Source: https://habr.com/ru/post/1726134/More articles:Gearman Architecture Requests - ruby-on-railsShareMem/обмен файлами с Delphi DLL - dlluser authentication and dht - authenticationConnecting to a WCF service in PHP that has NetTCP and BasicHttpBinding binding - phpStatic progress bar as table cell background - javascriptHow to permanently delete a file so that it becomes unrecoverable? - filesystemsWhat is the difference between $ {...} and! {...} in the Spark View Engine? - asp.net-mvcPrevent offline iphone webapp from opening links in Safari - safariLiterals prior to sparklight engine .netZend Db_NoRecordExists - checking multiple columns - zend-frameworkAll Articles