“列表索引超出范围”使用sys.argv [1]时 [英] "list index out of range" when using sys.argv[1]

查看:227
本文介绍了“列表索引超出范围”使用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

有人可以帮我吗?

当我在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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆