所以我有一個字串串列,我想把每個字串都放在我的代碼中。我該怎么做?
import requests
import json
import threading
import random
import socket
import struct
i = 0
def fg():
Api = "https://api.mcsrvstat.us/2/"
f = (List)
a = (Api f)
r = requests.get(a)
h = r.json()
print (json.dumps(h, indent = 2))
while i <= 10:
t1 = threading.Thread(target=fg)
t1.start()
t2 = threading.Thread(target=fg)
t2.start()
t3 = threading.Thread(target=fg)
t3.start()
t4 = threading.Thread(target=fg)
t4.start()
這將是字串串列,我希望它們每個都通過 fg 部分
127.0.1.1
127.0.2.1
127.0.3.1
127.0.4.1
我希望它輸出
https://api.mcsrvstat.us/2/127.0.1.1
https://api.mcsrvstat.us/2/127.0.2.1
https://api.mcsrvstat.us/2/127.0.3.1
https://api.mcsrvstat.us/2/127.0.4.1
uj5u.com熱心網友回復:
有很多方法可以實作這一目標。這是其中之一:
from concurrent.futures import ThreadPoolExecutor
import requests
import json
IP_ADDRESSES = ['127.0.1.1', '127.0.2.1', '127.0.3.1', '127.0.4.1']
def fg(ip_address):
url = f'https://api.mcsrvstat.us/2/{ip_address}'
with requests.Session() as session:
try:
(r := session.get(url)).raise_for_status()
return json.dumps(r.json(), indent=2)
except Exception as e:
return e
def main():
with ThreadPoolExecutor() as executor:
for future in [executor.submit(fg, ip_address) for ip_address in IP_ADDRESSES]:
print(future.result())
if __name__ == '__main__':
main()
uj5u.com熱心網友回復:
您可以在函式內回圈并使用 f 字串來格式化正確的:
strings = ["127.0.1.1", "127.0.2.1", "127.0.3.1", "127.0.4.1", ......]
def fg(strings):
for string in strings:
Api = f"https://api.mcsrvstat.us/2/{string}"
r = requests.get(Api)
h = r.json()
print (json.dumps(h, indent = 2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381627.html
