Anshul Solanki
Anshul Solanki

Reputation: 39

unable to get sys.argv[1] value

I am trying to execute a very simple script. It only prints the first argument passed.

The code is

import sys
def check(argument):
  '''Open, read, and print a file.'''
  print argument

if __name__ == "__main__":
  check(sys.argv[1])

however when i execute from command line, i always get this error

C:\>sample.py myname

Traceback (most recent call last):
  File "C:\sample.py", line 7, in <module>
    check(sys.argv[1])
IndexError: list index out of range

Any help

Upvotes: 1

Views: 1313

Answers (2)

Jeff Ames
Jeff Ames

Reputation: 2044

This might be a Windows issue: http://bugs.python.org/issue7936

Upvotes: 1

orlp
orlp

Reputation: 117691

Your script is fine, the way you execute it is wrong.

C:>sample.py myname

This uses windows file extension detecting to launch it with the python interpreter. Arguments might get lost in this way. Try executing it like this:

C:>python sample.py myname

Also, see issue 7936.

Upvotes: 5

Related Questions