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

2024-04-25 13:35:20 发布

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

我尝试使用下面的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]传递。你知道吗


Tags: 对象代码inimportforlen站点os
3条回答

尝试使用Python的字符串格式,例如:

"This string uses an %s" %(argument)将变为“此字符串使用参数”

像这样:

print(os.system('curl  write-out "%%{http_code}\n"  silent  output /dev/null "https://%s.wellsfargo.com"') % (servers[i])

更多信息:https://powerfulpython.com/blog/python-string-formatting/

只需使用requests库,而不是使用shell来运行curl

for s in servers:
    resp = requests.get(s)
    print(resp.status_code)

因为您不关心响应的主体,只关心它是否响应,所以可以通过使用head函数而不是get来节省带宽,只从服务器检索头。你知道吗

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

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

但是,如果服务器包含引号等,上面的内容仍然会出错

最好在这里使用^{}并向其传递一个参数列表,如:

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
    )

相关问题 更多 >