如何从列表python中提取值?

时间:2016-03-18 13:26:32

标签: python list dictionary pyyaml

我正在使用pyyaml,我需要在yaml中描述服务器配置,然后使用此列表中的参数运行脚本:

$CONTROLLER = new homeController();

然后我从yaml获取这些数据:

Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
    If Me.WindowState = FormWindowState.Minimized Then
        Notif.Visible = True
        Notif.BalloonTipText = "Copying"
        Notif.BalloonTipTitle = "Serious Copying"
        Notif.ShowBalloonTip(5000)
        Notif.Text = "Serious Copying"
        ShowInTaskbar = False
        Me.Visible = False

    End If
End Sub

Private Sub notifycn1_DoubleClick(sender As Object, e As EventArgs) Handles notifycn1.DoubleClick
    Me.Visible = True
    Me.show()
    ShowInTaskbar = True
    Notif.Visible = False
    Me.WindowState = FormWindowState.Normal
End Sub

然后我用这个列表中的args调用bash脚本:

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
...

在这种情况下如何通过用户?每个服务器的用户数可能不同,我需要以某种方式将其作为args传递。 或者可能是将每个服务器的用户名放到列表中,并对密码执行相同的操作,然后将其作为2个args传递给2个列表?

2 个答案:

答案 0 :(得分:1)

您可以添加一个变量来保存用户:

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)

您需要修改listcomp以从s["users"]中提取所需的字段。

答案 1 :(得分:1)

您应该将命令构建到变量中并将其扩展到所有用户:

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

然后使用以下内容致电call

    subprocess.call(cmd, shell=False)

你不能把列表作为@srowland的第一个参数a放在字符串列表的末尾:

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

将引发child_exception:

TypeError: execv() arg 2 must contain only strings