我正在尝试使用以下 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/