Python 使用 sys.argv[1] 时出现“列表索引超出范围”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15121717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:24:12  来源:igfitidea点击:

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

pythonpython-3.xcommand-line-arguments

提问by user1978826

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".

我正在编写一个简单的 Python 客户端和服务器,它可以很好地在我的代码中传递服务器地址,但是,我希望用户能够输入服务器地址并在不正确时抛出和错误。当我有下面的代码时,我从终端收到一条错误消息“列表索引超出范围”。

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.

当我在 python 中运行我的客户端程序时,我希望能够输入一个地址来连接并将其存储在服务器中。我通过键入 programname.py 直接从命令行运行该程序。服务器已经在运行,侦听传入的连接。

采纳答案by Jason Sperske

With this Python:

使用这个 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

我认为您没有向 Python 脚本传递参数

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:"))