IndexError: list index out of range in PyCharm

Question:

import subprocess
import sys

video_link, threads = sys.argv[1], sys.argv[2]
subprocess.call([
   "youtube-dl",
    video_link,
   "--external-downloader",
   "aria2c",
   "--external-downloader-args",
   "-x"+threads
])

Whenever I run the code the following error pops up. Help me please

_link, threads = sys.argv[1], sys.argv[2]

IndexError: list index out of range

Asked By: Mithilesh

||

Answers:

You are getting this error because your sys.argv has fewer than 3 items.

What does sys.argv store?

It stores the arguments passed to your script by the command line.

For instance. If you run python myscript.py an_arg another_one the values stored in sys.argv are going to be ['myscript.py', 'an_arg', 'another_one'].

Please, take your time to check the docs on sys.argv.

Answered By: Bonifacio2

You are most likely missing the arguments.

When you run,

python myscript.py arg1 arg2

sys.argv is a list with
myscript.py at sys.argv[0],arg1 at sys.argv[1], etc

So consider using if conditions or try-except to check if we have necessary arguments to unpack:

import subprocess
import sys

if len(sys.argv)>2:

    myscript.pyvideo_link, threads = sys.argv[1], sys.argv[2]
    subprocess.call([
   "youtube-dl",
    video_link,
   "--external-downloader",
   "aria2c",
   "--external-downloader-args",
   "-x"+threads
])

else:
    print('Missing Video link and thread arguments')
    #raise Error if desired
Answered By: Prayson W. Daniel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.