Threading python
I'm making a bot that parses subscribers of the entered account to log into the category of business accounts and for the presence of an avatar. I want to do parsing in four threads, but it turns out that the loop just runs four times. tell me how to do it correctly
import instaloader
import threading
L = instaloader.Instaloader()
L.login(login, password) # (log in)
nickname = str(input('Enter a nickname '))
# Checking followers without pic
followers_no_pic = []
# Checking the list of subscribers on existing business accounts
check_business = []
# Create list of followers
followers_list = []
print(f'Analysisof user {nickname}'
f'\nThe process may take some time, please wait')
# NICK FROM USER
Profile = instaloader.Profile.from_username(L.context, nickname)
def s(num):
for followers in Profile.get_followers():
followers_list.append(followers.username)
account = instaloader.Profile.from_username(L.context, followers.username)
if account.is_business_account is True:
check_business.append(account.is_business_account)
pic = account.profile_pic_url
pic = str(pic)
print('P r o c e s s')
if "https://instagram" in pic:
followers_no_pic.append(pic)
else:
pass
t1 = threading.Thread(target=s, args=(0.1,))
t2 = threading.Thread(target=s, args=(0.1,))
t3 = threading.Thread(target=s, args=(0.1,))
t4 = threading.Thread(target=s, args=(0.1,))
s(1)
t1.start()
t2.start()
t3.start()
t4.start()
print(f'User {nickname}'f'\nNumber of subscribers: {len(followers_list)}')
print(f'\nWithout pics: {len(followers_no_pic)}')
print(f'\nBusiness Accounts: {len(check_business)}')
# bot analytics: account name, number of subscribers, subscribers without avatars and business accounts
Solution 1:
You can use a Threadpool that splits the processing in this example into 4 threads so you can give it a list of inputs and a function and it will run 4 Threads parallel until all items in the input list got processed.
from multiprocessing.pool import ThreadPool
with ThreadPool(processes=4) as pool:
results = pool.map(s, [1, 2, 3, 4, 5])
print(results)