“列表索引超出范围"使用 sys.argv[1] 时 [英] "list index out of range" when using sys.argv[1]
问题描述
我正在编写一个简单的 Python 客户端和服务器,它可以很好地在我的代码中传递服务器地址,但是,我希望用户能够输入服务器地址并在不正确时抛出和错误.当我有下面的代码时,我从终端收到一条错误消息列表索引超出范围".
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.
当我在 python 中运行我的客户端程序时,我希望能够输入一个地址来连接并将其存储在服务器中.我通过键入 programname.py 直接从命令行运行该程序.服务器已在运行,侦听传入连接.
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.
推荐答案
有了这个 Python:
With this Python:
import sys
print(sys.argv)
并使用此命令调用:
>python q15121717.py 127.0.0.1
我得到这个输出:
['q15121717.py', '127.0.0.1']
我认为您没有向 Python 脚本传递参数
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:"))
这篇关于“列表索引超出范围"使用 sys.argv[1] 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!