第一次使用输入userid运行脚本时,如果用户在线,它将正常运行,直到打印(f'{username}, {userid}' + '仍然在线…')卡住。 当用户离线时,当userid == str(ps['user_id']):不再为真时,程序不会继续执行else操作。 它类似于str(ps['user_id']):在调用脚本时从不更新。
userid = input('Input userID: ')
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
while True: # Main loop to run if a user is online
for ps in data['result']['page']['list']:
if userid == str(ps['user_id']): # If a user is online print details
username = ps['nick_name']
print('Username: ' + ps['nick_name'])
print('UserID: ' + str(ps['user_id']))
while userid == str(ps['user_id']): # Look if the user is still online (is in the json response)
print(f'{username}, {userid}' + ' is still online...')
time.sleep(3)
else: # If user go offline(is not in the json response), break and restart main loop(first while loop).
break
print('Waiting for ' + f'{userid}' + ' to get online...') # Message until user go online again (is found in the json response).
time.sleep(5)
问题来源StackOverflow 地址:/questions/59380219/how-do-i-get-this-while-loop-and-json-response-to-work
您不会在循环的任何地方更新数据,因此每次迭代都使用相同的陈旧数据。您可以在time.sleep(5)之前将生成数据的三行代码添加到循环中。这将给你更新的数据,并应解决你的问题。
userid = input('Input userID: ')
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
userList = data['result']['page']['list']
isOnline = 0
while True: # Main loop to run if a user is online
hasLoggedIn = 0
for user in userList:
if str(user['user_id']) == userid and isOnline == 0: # If a user is online print details
username = user['nick_name']
print('Username: ' + user['nick_name'])
print('UserID: ' + str(user['user_id']))
print(f'{username}, {userid}' + ' is now online...')
isOnline = 1
hasLoggedIn = 1
time.sleep(3)
elif str(user['user_id']) == userid and isOnline == 1:
print(f'{username}, {userid}' + ' is still online...')
hasLoggedIn = 1
time.sleep(3)
if hasLoggedIn == 0:
print('Waiting for ' + f'{userid}' + ' to get online...') # Message until user go online again (is found in the json response).
isOnline = 0
time.sleep(5)
response = requests.post('website.com/api', headers=headers, data=data)
json_data = json.dumps(response.json(), indent=2)
data = json.loads(json_data)
userList = data['result']['page']['list']
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。