Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将带键的字典传递给函数_Python_Python 3.x - Fatal编程技术网

Python 将带键的字典传递给函数

Python 将带键的字典传递给函数,python,python-3.x,Python,Python 3.x,我是Python世界的新手,所以我不知道我是否会用正确的方式解释它 我有一个多线程脚本,其中线程函数只有很少的变量,2个必需变量和*args。在*args中,我希望传递对字典键的调用,但将其作为变量传递。让我向您展示代码,以便您更好地理解: 编辑:正确的代码示例 import threading routers = [] def list_file(file, separator=None): if separator: return [line.strip().s

我是Python世界的新手,所以我不知道我是否会用正确的方式解释它

我有一个多线程脚本,其中线程函数只有很少的变量,2个必需变量和
*args
。在
*args
中,我希望传递对字典键的调用,但将其作为变量传递。让我向您展示代码,以便您更好地理解:

编辑:正确的代码示例

import threading

routers = []


def list_file(file, separator=None):
    if separator:
        return [line.strip().split(separator) for line in open(str(file), "r").readlines()]
    else:
        return [line.strip() for line in open(str(file), "r").readlines()]

def do_something(target, command, *args):
    if command == "one":
        print(target, "option one", args)
    if command == "two":
        print(target, "option two", args)
    else:
        print("No valid command")


def thread(targets, cmd, *args):
    try:
        threads = list()
        for x in targets:
            th = threading.Thread(target = cmd, args = (x["hostname"],) + args)
            threads.append(th)
            th.start()

    except KeyboardInterrupt:
        print("\n\n* Program aborted by user. Exiting...\n")
        raise


for x in list_file("./hosts.txt", ","):
    routers += [{"hostname": x[0], "dmvpn_ip": x[1]}]


thread(routers,do_something, 'one', 'hello' + x["dmvpn_ip"])
基本上,如果您看到“线程(路由器,做些什么,'one','hello'+x[“dmvpn\u ip”]”,我想在th变量“th=threading.thread(target=cmd,args=(x[“hostname”],)+args)中传递x[“dmvpn\u ip”],在thread()中完成

但它会引发以下错误,如果我将其作为字符串发送,则不会执行我想要的操作:

Traceback (most recent call last):
  File "/test.py", line 38, in <module>
    thread(routers,do_something, 'one', 'hello' + x["dmvpn_ip"])
TypeError: list indices must be integers or slices, not str
回溯(最近一次呼叫最后一次):
文件“/test.py”,第38行,在
线程(路由器,做点什么,'one','hello'+x[“dmvpn\u ip”])
TypeError:列表索引必须是整数或片,而不是str

好的,所以我用另一种方式做了:我从线程函数中取出for循环,并在外部执行,这样我就可以直接传递键的值。现在看起来是这样的:

import files
routers = []
threads = list()

for x in files.list_file("./hosts.txt", ","):
    routers += [{"hostname": x[0], "dmvpn_ip": x[1]}]

for y in routers:
    thread(threads,y['hostname'],router_cmd, 'normal', 'sh dmvpn interface ' + y['dmvpn_ip'])
和线程代码:

def thread(threads, target, cmd, *args):
    try:
        th = threading.Thread(target = cmd, args = (target,) + args)
        threads.append(th)
        th.start()

    except KeyboardInterrupt:
        print("\n\n* Program aborted by user. Exiting...\n")
        raise

我在你的代码中没有看到任何“疯狂”的东西。同时,我不明白您想问什么。@sid-m是您在第二个代码块中看到的,在线程调用中,传递的第三个变量是x[“dmvpn_ip”],但这不起作用,因为它会引发类型错误(类型错误:列表索引必须是整数或片,而不是str)但是我想传递它,因为我想在线程函数的for循环中读取字典的这个键欢迎使用SO。请提供您的问题的详细说明。还有,实际的问题是什么?嗨@MaxPower我已经编辑了这篇文章。让我知道这个例子现在是否有效。谢谢