-6
import sys

def Hello(name):
   name = name + '!!!'
   print 'Hello' ,  name


def main():
    Hello(sys.argv[1])


if __name__ == '__main__':
       main()

Here is the error

Traceback (most recent call last):
  File "D:\pythonPractice\firstPython.py", line 13, in <module>
    main()
  File "D:\pythonPractice\firstPython.py", line 9, in main
    Hello(sys.argv[1])
IndexError: list index out of range

I have also tried sys.argv[2] but error remains

2
  • 2
    Your code doesn't match the error. None of your lines contain Hello(sys.argv[1]).
    – nneonneo
    Aug 28, 2012 at 7:57
  • I ran this script on my box (Python 2.7.3) and it worked without any problems. I'm a bit confused that your error message says sys.argv[1] is out of range but in your code you are using sys.argv[0]. Maybe you are running the wrong script?
    – akluth
    Aug 28, 2012 at 7:58

2 Answers 2

3

First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:

def main():
    Hello(sys.argv[1])

As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:

python helloprog Pax

You would find a more robust main as:

def main():
    if len(sys.argv) < 2:
        Hello("whoever you are")
    else:
        Hello(sys.argv[1])

which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.

1
  • @darpan1118 the point is that you need to use the if and else blocks, just like in paxdiablo's answer. sys.argv is a python list (click for a great and short tutorial) and if you pass no command line arguments from the command line, you get your error, except you do the if-else block like above. If you run this from an IDE instead of a command line or terminal, you need to find a way to specify command line arguments (also called command line parameters).
    – n611x007
    Apr 17, 2013 at 12:38
1

Have you used

sys.argv[0]

Since this returns a list , you may not have elements >1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.