Ошибка индекса sys.argv вне диапазона - PullRequest
0 голосов
/ 07 июня 2018

Я пытаюсь запустить этот сценарий, который захватывает RSS-каналы в среде "Thonny", но я просто продолжаю получать эту ошибку "IndexError: List index out of range"

Traceback (most recent call last):
File "C:\Users\uri\rssfeedfour.py", line 11, in <module>
url = sys.argv[1]
IndexError: list index out of range

Как решитьэто, чтобы избежать получения этой ошибки снова и снова.Я не уверен, как решить эту проблему, так как я новичок.Нужно ли мне это определять, если да, то как?или я мог бы взять это и пойти в другом направлении?Вот код

import feedparser
import time
from subprocess import check_output
import sys

#feed_name = 'TRIBUNE'
#url = 'http://chicagotribune.feedsportal.com/c/34253/f/622872/index.rss'

feed_name = sys.argv[1]
url = sys.argv[2]

db = 'http://feeds.feedburner.com/TheHackersNews'
limit = 12 * 3600 * 1000

current_time_millis = lambda: int(round(time.time() * 1000))
current_timestamp = current_time_millis()

def post_is_in_db(title):
    with open(db, 'r') as database:
        for line in database:
            if title in line:
                return True
    return False


def post_is_in_db_with_old_timestamp(title):
    with open(db, 'r') as database:
        for line in database:
            if title in line:
                ts_as_string = line.split('|', 1)[1]
                ts = long(ts_as_string)
                if current_timestamp - ts > limit:
                    return True
    return False

#
# get the feed data from the url
#
feed = feedparser.parse(url)

#
# figure out which posts to print
#
posts_to_print = []
posts_to_skip = []

for post in feed.entries:
    # if post is already in the database, skip it
    # TODO check the time
    title = post.title
    if post_is_in_db_with_old_timestamp(title):
        posts_to_skip.append(title)
    else:
        posts_to_print.append(title)

#
# add all the posts we're going to print to the database with the current timestamp
# (but only if they're not already in there)
#
f = open(db, 'a')
for title in posts_to_print:
    if not post_is_in_db(title):
        f.write(title + "|" + str(current_timestamp) + "\n")
f.close

#
# output all of the new posts
#
count = 1
blockcount = 1
for title in posts_to_print:
    if count % 5 == 1:
        print("\n" + time.strftime("%a, %b %d %I:%M %p") + '  ((( ' + feed_name + ' - ' + str(blockcount) + ' )))')
        print("-----------------------------------------\n")
        blockcount += 1
    print(title + "\n")
    count += 1

1 Ответ

0 голосов
/ 07 июня 2018

sys.argv - это список в Python, который содержит аргументы командной строки, передаваемые скрипту.sys.argv[0] содержит имя сценария, sys.argv[1] содержит первый аргумент и т. Д.

Чтобы предотвратить эту ошибку, необходимо указать аргументы командной строки при запуске сценария.Например, вы можете запустить этот сценарий без каких-либо ошибок с помощью

python rssfeedfour.py TRIBUNE http://chicagotribune.feedsportal.com/c/34253/f/622872/index.rss

. Вы также можете изменить сценарий так, чтобы он работал, используя аргументы по умолчанию, если вы не указали аргументы командной строки.

try:
    feed_name = sys.argv[1]
except IndexError:
    feed_name = 'TRIBUNE'

try: 
    url = sys.argv[2]
except IndexError:
    url = 'http://chicagotribune.feedsportal.com/c/34253/f/622872/index.rss'

Подробнее об обработке ошибок можно узнать здесь .

Хотя гораздо удобнее использовать библиотеку argparse .

...