简体   繁体   English

如何从列表python中提取值?

[英]How to extract values from list python?

I'm working with pyyaml and i need to describe the server configurations in yaml, then run script with arguments from this list: 我正在使用pyyaml,我需要用yaml描述服务器配置,然后使用此列表中的参数运行脚本:

servers:
  - server: server1
    hostname: test.hostname
    url: http://test.com
    users:
    - username: test
      password: pass
    - username: test1
      password: pass2
  - server: server2
    hostname: test.hostname2
    url: http://test2.com
    users:
    - username: test3
      password: pass
    - username: test4
      password: pass2
    - username: test5
      password: pass6
...

then I'm getting this data from yaml: 然后我从yaml获取此数据:

source = self._tree_read(src, tree_path)

and then I'm calling bash script with args from this list: 然后我从这个列表中用args调用bash脚本:

for s in source['servers']:
    try:
        subprocess.call(["/bin/bash", "./servers.sh",
                         s["server"],
                         s["hostname"],
                         s["url"],
                       **s["users"]**
                        ], shell=False)

How can I pass users in this case? 在这种情况下如何传递用户? The number of users can be different for each server and I need to pass it as args somehow. 每个服务器的用户数量可以不同,我需要以某种方式将其作为args传递。 Or may be is it possible to put usernames from each server to list, and do same with passwords and then pass it it as 2 args with 2 lists? 还是有可能将每个服务器的用户名放到列表中,并使用密码进行同样的操作,然后将其作为2个带有2个列表的参数传递给它?

you could add a variable to hold the users: 您可以添加一个变量来容纳用户:

for s in source["servers"]:
    # add any processing in the list comp to extract users
    user_list = [user["username"] for user in s["users"]]
    try:
        subprocess.call(["/bin/bash", "./servers.sh",
                         s["server"],
                         s["hostname"],
                         s["url"],
                         ",".join(user_list),
                         ], shell=False)

You'll need to modify the listcomp to extract the fields you want from s["users"] . 您需要修改listcomp以从s["users"]提取所需的字段。

You should build the command into a variable and extend that with all the users: 您应该将命令构建到变量中,并将其扩展给所有用户:

    cmd = ["/bin/bash", "./servers.sh", 
                     s["server"],
                     s["hostname"],
                     s["url"],
                    ]
    cmd.extend(s["users"])

then call call with that: 然后打电话call那个:

    subprocess.call(cmd, shell=False)

You cannot put a list at the end of the list of strings as the first argument a as @srowland does: 您不能像@srowland一样将列表放在字符串列表的末尾作为第一个参数a:

subprocess.call(['/bin/bash', 'echo', 'hello', ['good', 'evening']], shell=False)

will raise a child_exception: 将引发child_exception:

TypeError: execv() arg 2 must contain only strings

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

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