Learner Learner - 1 month ago 6
Python Question

IndexError wrong error Python

I am deleting phantom files we have in Slack. Below is my script. I am getting an IndexError list index out of range error. Can someone provide assistance on what I am doing wrong.

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])


It gives an error on the last line 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

Answer

You could solve the error like so, but that'll just tell you how you need to actually run this file.

In other words, Please provide a value for the API Token

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)

Something like Desktop\> python Slacker.py xxxxAPI_TOKENxxxx

I might re-write that try-except to actually validate the length of the arguments, though

if __name__ == "__main__":
    if len(sys.argv) < 1:
        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])
Comments