python - 需要在 bash 中传递 python 数组中的对象

标签 python bash python-2.7

我正在尝试使用以下 python 代码片段获取三个站点的响应代码。但想知道如何解析数组中的每个对象以通过 curl 调用中的 for 循环。

import os

servers = ["google", "yahoo", "nonexistingsite"]
for i in range(len(servers)):
    print(os.system('curl --write-out "%{http_code}\n" --silent --output'
                    ' /dev/null "https://servers[i].com"'))

使用上面的代码,它不会通过 servers[i] 传递。

最佳答案

您需要执行字符串格式化,例如:

import os

servers = ["google", "yahoo", "nonexistingsite"]
for server in servers:
  print(os.system('curl --write-out "%{{http_code}}\\n" --silent --output /dev/null "https://{}.wellsfargo.com"'.format(server)))

但是,如果服务器包含引号等,上述仍然会出错。

这里使用subprocess.run可能会更好并将参数列表传递给它,例如:

servers = ["google", "yahoo", "nonexistingsite"]
for server in servers:
    p = subprocess.run(
        [
            'curl'
            '--write-out',
            '%{http_code}\\n',
            '--silent',
            '--output'
            '/dev/null',
            'https://{}.wellsfargo.com'.format(server)
        ],
        shell=True,
        capture_output=True
    )

关于python - 需要在 bash 中传递 python 数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025216/

相关文章:

python - 在 Django 中从外部 Active Directory 提取数据

python - chalice helloworld 部署问题

python - 在 Sqlite 中对多索引大型数据库表进行排序

c - 在 C 应用程序中嵌入 Python 应用程序

python - Folium map 未在 Django 网页中显示

Python Urllib2 只读文档的一部分

bash - 在远程 tomcat 服务器上部署 ansible 和 bash

bash - bash 脚本中的 while 循环在 vim 中没有正确突出显示

bash - 在 Bash 中将定界字符串解析为数组 - 为什么 "$var"与 $var 不同,尽管 $var 没有空格?

python - 将项目附加到 Urwid 中的 SimpleFocusListWalker