我正在删除Slack中的幻像文件。下面是我的脚本。我得到一个IndexError列表索引超出范围错误。有人可以帮我解决我的错误。
import Slacker
import sys
import time
from datetime import timedelta, datetime
def main(token, weeks=4):
slack = Slacker(token)
total = slack.files.list(count=1).body['paging']['total']
num_pages = int(total/1000.00 + 1)
print("{} files to be processed, across {} pages".format(total, num_pages))
files_to_delete = []
ids = []
count = 1
for page in range(num_pages):
print ("Pulling page number {}".format(page + 1))
files = slack.files.list(count=1000, page=page+1).body['files']
for file in files:
print("Checking file number {}".format(count))
if file['id'] not in ids:
ids.append(file['id'])
if datetime.fromtimestamp(file['timestamp']) < datetime.now() - timedelta(weeks=weeks):
files_to_delete.append(file)
print("File No. {} will be deleted".format(count))
else:
print ("File No. {} will not be deleted".format(count))
count+=1
print("All files checked\nProceeding to delete files")
print("{} files will be deleted!".format(len(files_to_delete)))
count = 1
for file in files_to_delete:
print("Deleting file {} of {}".format(count, len(files_to_delete)))
slack.files.delete(file_=file['id'])
print("Deleted Successfully")
count+=1
return count-1
if __name__ == "__main__":
try:
token = sys.argv[1:]
except IndexError:
print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token")
sys.exit(2)
main(token[0])
它在最后一行main(token [0])上给出错误。
Traceback (most recent call last):
File "C:/Users/aqureshi/Desktop/Programming/Slacker.py", line 50, in <module>
main(token[0])
IndexError: list index out of range
答案 0 :(得分:1)
名义上你可以通过在try / except块中移动main(token[0])
来解决问题。但这是有问题的,因为程序中的任何其他IndexError
都可能被错误地报告为命令使用问题。最好明确检查输入参数。它还为您提供了检查常见帮助标记的机会。
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] in ('-h', '--help', '/?'):
print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token")
sys.exit(2)
main(sys.argv[1])
答案 1 :(得分:0)
您可以像这样解决错误,但这只是告诉您如何实际运行此文件。
换句话说,请提供API令牌的值
if __name__ == "__main__":
try:
token = sys.argv[1:]
main(token[0])
except IndexError:
print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token")
sys.exit(2)
像Desktop\> python Slacker.py xxxxAPI_TOKENxxxx
我可能会重写那个尝试 - 除了实际验证参数的长度,但是
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token")
sys.exit(2)
token = sys.argv[1:]
main(token[0])
答案 2 :(得分:0)
期待这个
token = sys.argv[1:]
抛出异常是错误的。它永远不会,如果sys.argv
本身只有长度1,它将继续返回一个空列表。然后
main(token[0])
是你的IndexError
而是检查sys.argv
变量的长度。有一个或多个参数应该至少为2。
import sys
def main(x):
print(x)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token")
sys.exit(2)
main(sys.argv[1])