我试图改进我朋友的Python&Twitch帐户检查工具' (基本上从文本文件中获取用户名列表,并检查它们是否可用或在Twitch.tv上获取)。我打算以一种将可用用户名输出到文本文件(与原始列表位于同一位置)的方式对其进行改进。我实际上正在搜索Stack Overflow,并找到了一个解释'如何实际输出一个列表(我将可用的用户名放入一个单独的列表中)到文本文件中。
运行脚本时,它可以正常工作,直到它应该保存可用的用户名。然后,我收到以下错误:
Traceback (most recent call last):
File "multithreadtwitchchecker.py", line 44, in <module>
output_available_usernames('availableusernames.txt')
File "multithreadtwitchchecker.py", line 37, in output_available_usernames
AVAILABLE_USERNAMES = f.write(AVAILABLE_USERNAMES.split('\n'))
AttributeError: 'list' object has no attribute 'split'
以下是代码:
from multiprocessing.pool import ThreadPool
import re
import requests
import sys
try:
input = raw_input
except NameError:
pass
TWITCH_URL = "https://www.twitch.tv/{username}"
TWITCH_REGEX = re.compile(r"^[a-zA-Z0-9_]{4,25}$")
MAX_THREADS = 25
MESSAGES = {True: "Available", False: "Taken"}
AVAILABLE_USERNAMES = []
def read_valid_usernames(filename):
"""Reads a list of usernames and filters out invalid ones."""
try:
with open(filename, "r") as fin:
return [username for username in map(str.strip, fin) if TWITCH_REGEX.match(username)]
except IOError:
sys.exit("[!] '{}' - Invalid File".format(filename))
def username_available(username):
"""Checks if a 404 response code is given when requesting the profile. If it is, it is presumed to be available"""
try:
return username, requests.get(TWITCH_URL.format(username=username)).status_code == 404
AVAILABLE_USERNAMES.append(username)
except Exception as e:
print(e)
def output_available_usernames(filename):
"""Gets a filename to output to and outputs all the valid usernames to it"""
global AVAILABLE_USERNAMES
f = open(filename, 'w')
AVAILABLE_USERNAMES = f.write(AVAILABLE_USERNAMES.split('\n'))
usernames = read_valid_usernames(input("Enter path to list of usernames: "))
for username, available in ThreadPool(MAX_THREADS).imap_unordered(username_available, usernames):
print("{:<{size}}{}".format(username, MESSAGES.get(available, "Unknown"), size=len(max(usernames, key=len)) + 1))
output_available_usernames('availableusernames.txt')
答案 0 :(得分:1)
好吧,写一个文件可以这样做:
def output_available_usernames(filename):
global AVAILABLE_USERNAMES
with open(filename, 'w') as f:
for name in AVAILABLE_USERNAMES:
f.write(name + '\n')
正如jonrsharpe所说,split
的方向是错误的。
但是,您的代码现在有一个更深层次的问题。在 AVAILABLE_USERNAMES
语句后附加到return
,以便代码永远不会执行,AVAILABLE_USERNAMES
将始终为空。你想要这样的东西:
def username_available(username):
"""Checks if a 404 response code is given when requesting the profile. If it is, it is presumed to be available"""
try:
if requests.get(TWITCH_URL.format(username=username)).status_code == 404:
AVAILABLE_USERNAMES.append(username)
return username, True
else:
return username, False
except Exception as e:
print(e)