How do I use user input to invoke a function in Python?

This question already has an answer here:

  • Calling a function of a module by using its name (a string) 10 answers
  • Create a raw input with commands inside a Python script 1 answer

  • The error is because function names are not string you can't call function like 'func1'() it should be func1() ,

    You can do like:

    {
    'func1':  func1,
    'func2':  func2,
    'func3':  func3, 
    }.get(choice)()
    

    its by mapping string to function references

    side note : you can write a default function like:

    def notAfun():
      print "not a valid function name"
    

    and improve you code like:

    {
    'func1':  func1,
    'func2':  func2,
    'func3':  func3, 
    }.get(choice, notAfun)()
    

    If you make a more complex program it is probably simpler to use the cmd module from the Python Standard Library than to write something.
    Your example would then look so:

    import cmd
    
    class example(cmd.Cmd):
        prompt  = '<input> '
    
        def do_func1(self, arg):
            print 'func1 - call'
    
        def do_func2(self, arg):
            print 'func2 - call'
    
        def do_func3(self, arg):
            print 'func3 - call'
    
    example().cmdloop()
    

    and an example session would be:

    <input> func1
    func1 - call
    <input> func2
    func2 - call
    <input> func3
    func3 - call
    <input> func
    *** Unknown syntax: func
    <input> help
    
    Undocumented commands:
    ======================
    func1  func2  func3  help
    

    When you use this module every function named do_* will be called when the user inputs the name without the do_ . Also a help will be automatically generated and you can pass arguments to the functions.

    For more informations about this look into the Python manual (here) or into the Python 3 version of the manual for examples (here).


    你可以使用locals

    >>> def func1():
    ...     print 'func1 - call'
    ... 
    >>> def func2():
    ...     print 'func2 - call'
    ... 
    >>> def func3():
    ...     print 'func3 - call'
    ... 
    >>> choice = raw_input()
    func1
    >>> locals()[choice]()
    func1 - call
    
    链接地址: http://www.djcxy.com/p/55164.html

    上一篇: 来自字符串的Python调用函数

    下一篇: 我如何使用用户输入来调用Python中的函数?