如何在Python中从dict获取所需的值

2024-04-19 15:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个功能:

def render(self, src, **kwargs):
    dict = self._tree_read(src, self.src_tree_path)

dict包含:

[('hosts', [{'username': 'test-user', 'url': 'http://example.com', 'hostname': 'test-host'}, {'username': 'test-user2', 'url': 'http://example.com2', 'hostname': 'test-host2'}])]

然后我尝试运行另一个bash脚本,并将参数从dict传递给它(dict中有两个配置,所以我需要运行子进程两次):

subprocess.call(["/bin/bash", "/opt/hosts.sh", "username", "url", "hostname"], shell=False)

但是没有成功,请帮助我。谢谢您!你知道吗


Tags: testself功能srcbashtreehttpurl
1条回答
网友
1楼 · 发布于 2024-04-19 15:31:50

您所称的dict实际上是一个包含元组的列表,其中包含一个dict列表。你知道吗

首先,dict是一个内置变量,不要重写它,请调用其他变量。你知道吗

从那里,您可以迭代这些结果,以使用所需的值多次运行该子流程。你知道吗

def render(self, src, **kwargs):
   results = self._tree_read(src, self.src_tree_path)

   for host in result[0][1]:
      subprocess.call(["/bin/bash", "/opt/hosts.sh", host["username"], host["url"], host["hostname"]], shell=False) 

相关问题 更多 >