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

I am having an issue with the following section of Python code:

import sys  
import requests  
import firebase_admin  
from firebase_admin import credentials  
from firebase_admin import storage  
image_url = sys.argv[1]  
cred = credentials.Certificate('certificate.json')  
firebase_admin.initialize_app(cred,{'storageBucket':'gs://rpi-demo-6d21d.appspot.com'})  
bucket = storage.bucket()  
image_data = requests.get(image_url).content  
blob = bucket.blob('happy.jpg')  
blob.upload_from_string(image_data,content_type='image/jpg')  
print(blob.public_url)

Specifically the error is as follows:

Traceback (most recent call last):
File "demo4.py", line 6, in <module>
image_url = sys.argv[1]
IndexError: list index out of range

Solution #1:

sys.argv list is populated from the command line arguments passed to the script, so in case none are provided it’s expected to get an error like

Traceback (most recent call last):
File "demo4.py", line 6, in <module>
image_url = sys.argv[1]
IndexError: list index out of range

An easy repro is to put

import sys
print(sys.argv[1])

in demo.py and run it using python demo.py. You’ll get the output

$ python demo.py
Traceback (most recent call last):
  File "demo.py", line 2, in <module>
    print(sys.argv[1])
IndexError: list index out of range

but if you pass an argument to it using python demo.py foo you’ll get the desired output:

$ python demo.py foo
foo

Specifically for your example, looks like when calling demo4.py script you’re not passing image url command line argument. You can pass it using python demo4.py <image_url_goes_here>.

Respondent: Taras Tsugrii

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.