Python Модуль sys, ошибка при запуске IndexError: list index out of range

from datetime import datetime

import requests

API_KEY = "..."


def convert_currency(src, dst, amount):
    """converts `amount` from the `src` currency to `dst` using the free account"""
    url = f"http://data.fixer.io/api/latest?access_key={API_KEY}&symbols={src},{dst}&format=1"
    data = requests.get(url).json()
    if data["success"]:
        # request successful
        rates = data["rates"]
        # since we have the rate for our currency to src and dst, we can get exchange rate between both
        # using below calculation
        exchange_rate = 1 / rates[src] * rates[dst]
        last_updated_datetime = datetime.fromtimestamp(data["timestamp"])
        return last_updated_datetime, exchange_rate * amount


    if __name__ == "__main__":
      import sys

    source_currency = sys.argv[1]
    destination_currency = sys.argv[2]
    amount = float(sys.argv[3])

    last_updated_datetime, exchange_rate = convert_currency(source_currency, destination_currency, amount)
    # upgraded account, uncomment if you have one
    # last_updated_datetime, exchange_rate = convert_currency source_currency, destination_currency, amount)
    print("Last updated datetime:", last_updated_datetime)
    print(f"{amount} {source_currency} = {exchange_rate} {destination_currency}")

Всем привет. Пытался разобраться с модулем sys, чтобы сделать CLI интерфейс, но при запуске выдает ошибку. Не подскажите в чем именно проблема? Заранее спасибо.

source_currency = sys.argv[1]
IndexError: list index out of range

Ответы (1 шт):

Автор решения: Roman-Stop RU aggression in UA

Проблема в том, что вы неправильно вызываете свое приложение.

sys.argv содержит параметры, которые вы передали в командной строке своему приложению. То есть, если запускаете приложение командой:

python app.py 1 2 3

то в sys.argv будет список ['app.py', '1', '2', '3']. index out of range в общем означает, что элемента с таким индексом в списке нет. В вашем же случае это означает, что вы не передали параметры в командной строке, как того ожидает этот код.

Чтоб исправить просто передайте нужные параметры при запуске.

→ Ссылка