Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 369
user1978826 Avatar asked Feb 27 '13 20:02

user1978826


People also ask

How do I fix list index out of range in Python?

To fix this, you can modify the parameter in the range() function. A better solution is to use the length of the list as the range() function's parameter. The code above runs without any error because the len() function returns 3. Using that with range(3) returns 0, 1, 2 which matches the number of items in a list.

How do I use SYS argv 1 in Python?

To use, sys. argv in a Python script, we need to impo r t the sys module into the script. Like we import all modules, "import sys" does the job. Ideally, we want this at the top of the script, but anywhere before we use the sys.

What is index out of range error?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

What does Sys argv do in Python?

sys. argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program.


1 Answers

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:"))
like image 174
Jason Sperske Avatar answered Oct 26 '22 03:10

Jason Sperske