"list index out of range" when using sys.argv[1]

41,250

With this Python:

import sys

print(sys.argv)

And invoked with this command:

>python q15121717.py 127.0.0.1

I get this output:

['q15121717.py', '127.0.0.1']

I think you are not passing a argument to your Python script

Now you can change your code slightly to take a server form the command line or prompt for a server when none is passed. In this case you would look at something like this:

if len(sys.argv) > 1:
    print(sys.argv[1])
else:
    print(input("Enter address:"))
Share:
41,250
user1978826
Author by

user1978826

Updated on February 28, 2020

Comments

  • user1978826
    user1978826 over 4 years

    I am writing a simple Python client and server, which works fine passing the server address within my code, however, I want the user to be able to enter the server address and throw and error if its incorrect. When I have the code below I get a error message from the terminal "list index out of range".

    server = (sys.argv[1])
    serverAdd = (server, '65652') # server address and port number
    

    Can anyone help me with this please.

    When I run my client program in python I want to be able to enter a address to connect to and store that in server. I run the program directly from the command line by typing programname.py. The server is already running listening for incoming connections.

  • user1978826
    user1978826 over 11 years
    I think your right. I am i write in thinking that sys.argv[1] would be the second element etc...... so in the case above sys.argv['127.0.0.1']