通过在python上使用参数调用函数

时间:2015-11-27 11:26:38

标签: python python-2.7

在Python中使用** kwargs调用函数并从脚本获取输出的正确方法是什么? 我想使用这样的脚本:

python script.py <argument> "here description"

这是我的例子

class Task:
    pass

    def __init__(self, **kwargs):
        arguments = {'cre': 'create', 'inf': 'info', 'sre': 'search', 'com': 'comment'}
        arguments.update(kwargs)
        self.create = arguments['cre']
        self.action = arguments['inf']
        self.search = arguments['sre']
        self.comment = arguments['com']

    def create(description):
         print "Task in progress -->-->"

    def search(description):
        print "Searching for task"

    def info(description):
        print "Task Info"

    def comment(description):
        print "Comment task"

if __name__=='__main__':
    Task(**kwargs)

在目前的剧本中我得到:

Traceback (most recent call last):
  File "simple_function.py", line 39, in <module>
    Task(**kwargs)
NameError: name 'kwargs' is not defined

1 个答案:

答案 0 :(得分:1)

试试这个:

import sys

class Task(object):

    def __init__(self, **kwargs):

        functions_mapping = {
            'cre': self.create,
            'inf': self.info,
            'sre': self.search,
            'com': self.comment
        }

        for key, value in kwargs.items():
            self.description = value
            try:
                functions_mapping.get(key)()
            except TypeError:
                print "Please provide a correct function name: {}".format(', '.join([x for x in functions_mapping.keys()]))

    def create(self):
        print "Task in progress --> {}".format(self.description)

    def search(self):
        print "Searching for task --> {}".format(self.description)

    def info(self):
        print "Task Info --> {}".format(self.description)

    def comment(self):
        print "Comment task --> {}".format(self.description)


if __name__=='__main__':
    if len(sys.argv) > 1 and len(sys.argv) < 4:
        function, description = sys.argv[1:]
        my_dict = dict()
        my_dict[function] = description
        Task(**my_dict)

<强>输出:

➜  python stackoverflow.py com something_here
Comment task --> something_here

➜  python stackoverflow.py inf something_else
Task Info --> something_else

➜  python stackoverflow.py sre something_more
Searching for task --> something_more

➜  python stackoverflow.py cre somethingggggg
Task in progress --> somethingggggg

➜  python stackoverflow.py moo foobar
Please provide a correct function name: inf, sre, com, cre