-2

I have a problem with argv[1] in Python 3.8.2. This is my code:

from sys import *

def open_file(filename):
    print(filename)

def run():
    open_file(argv[1])

run()

And it shows error:

Traceback (most recent call last):
  File "*File*", line 9, in <module>
    run()
  File "*File*", line 7, in run
    open_file(argv[1])
IndexError: list index out of range

Can somebody help me?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

0

Are you sure that you call the script with the argument? Like this:

python myscript.py "First arg"

By the way,

from sys import *

is bad code. You should never do that. If you want to import a whole module, better do it like that:

import sys

Then to refer desired variable use name_of_module.name_of_variable:

sys.argv[1]
Midriaz
  • 180
  • 1
  • 8
0

argv is a list of all parameters entered behind python on your command line separated by spaces.

example: foo.py:

from sys import argv
print(argv)
print(argv[0])
print(argv[1])

command line:

python foo.py 1 2 3

stdout:

['foo.py', '1', '2', '3']
foo.py
1
Fmountains
  • 11
  • 2