简体   繁体   English

将参数传递给Python中作为菜单的字典中调用的函数

[英]Passing parameters to function called in a dictionary as menu in Python

I was asked to create a simple script to transfer data from a database to another one and to make it parametric as much as possible, including a selective menu for allowing the user to choose an operation. 我被要求创建一个简单的脚本,以将数据从数据库传输到另一个数据库,并使其尽可能参数化,包括一个允许用户选择操作的选择菜单。

As you know, Python doesn't have a switch-case statement and you can simulate a menu using a if-elif...else chain or using a dictionary . 如您所知,Python没有switch-case语句,您可以使用if-elif ... else链或使用Dictionary模拟菜单。

I opted for the dictionary, because of a more elegant way to do it: 我选择字典是因为这样做的方式更优雅:

options = {
        1: ('Create temp table', create_tmp_table),
        2: ('Write data in temp table', copy_to_temp),
        3: ('Trnasfer data from temp table to final table', copy_into_main_table),
        4: ('Delete temp table', delete_tmp_table),
        5: ('Exit', exit)
    }

Here comes my problem. 这是我的问题。 As you can see from the code, I have a function that creates a support table and takes as parameters the fields of a configuration file asked at the beginning of the script. 从代码中可以看到,我有一个函数,该函数创建一个支持表,并将脚本开始时要求的配置文件的字段作为参数。

When I call the function: 当我调用该函数时:

if __name__ == '__main__':

cfg_file = raw_input('Insert configuration file: ')

try:
    params = parse_config_file(cfg_file)
    dbs = init_connection(params.src_config, params.dst_config)
except ConfigParser.Error as e:
    print e
    raise Exception('File Parsing Error')
except psycopg2.DatabaseError as e:
    print e
    raise Exception('Connection Error')
else:
    create_menu()
    choice = raw_input('\nChoose an operation: ')
    if choice in options.iterkeys():
        func= options[choice][1]

For example choosing operation 1, it doesn't nothing. 例如选择操作1,它什么也没有。 I believe the fact that not passing any argument to the function (obviously), it does nothing. 我相信这样的事实:不(显然)不向函数传递任何参数,它什么也不做。 So, how can I give the arguments to properly call the function: 因此,我该如何给出参数以正确调用该函数:

def create_tmp_table(*varargs):
    name = raw_input('Scegli un nome per la tabella d\'appoggio')
    query = """ CREATE TABLE {0} (
                      SOME 
                      COLUMNS
                    );
                """.format(name)
    varargs[0].execute(query)
    varargs[1].commit()

Here is a simple output: 这是一个简单的输出:

DB TRANSFER 数据库传输

1 - Create temp table 1-创建临时表

2 - Write data in temp table 2-在临时表中写入数据

3 - Trnasfer data from temp table to final table 3-从临时表到最终表的Trnasfer数据

4 - Delete temp table 4-删除临时表

5 - Exit 5-退出

Choose an operation: 1 选择一个操作:1

Process finished with exit code 0 流程结束,退出代码为0

If I understand your issue correctly, all you need to do is call the function instead of just assigning it to a variable. 如果我正确理解了您的问题,那么您要做的就是调用函数,而不仅仅是将其分配给变量。 In other words, replace: 换句话说,替换为:

func= options[choice][1]

with: 与:

options[choice][1]()

Method dispatching using a dictionary works like this: 使用字典的方法分派如下所示:

def foo(arg1, arg2):
    ... some code ...

def bar(arg1, arg2):
    ... some code ...

dispatcher = {'option 1': foo,
              'option 2': bar}

selected_option = 'option 1'
arg1 = 'my first arg'
arg2 = 'my second arg'

dispatcher[selected_option](arg1, arg2)

You have to invoke the function you take from the dictionary, that's missing in your code. 您必须调用从字典中获取的函数,而您的代码中缺少该函数。 Also, you have to make sure that your functions in the dict accept the parameters you pass to it when you invoke the function. 同样,您必须确保dict中的函数接受调用函数时传递给它的参数。

As denoted in one of the comments, make sure the key is in the dictionary. 如注释之一所示,确保密钥在词典中。 It looks like you use the user input string to select from the dict but the dict keys are ints. 看起来您使用用户输入字符串从dict中进行选择,但是dict键是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM