So I have a list of strings and I want to put every string through my code. How would I do that?
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()
and this would be the list of strings and i would like each of them to go through the fg part
127.0.1.1
127.0.2.1
127.0.3.1
127.0.4.1
and i want it to output
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
CodePudding user response:
There are many ways to achieve this. Here's one of them:
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()
CodePudding user response:
You could loop through within the function and use f strings to format the correct :
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))