为什么我对sys.argv的调用无法识别?

时间:2015-03-24 01:44:39

标签: python udp client ping

我正在尝试实现UDP pinger程序的客户端。我目前收到此错误:

Traceback (most recent call last):
  File ".../UDPClient.py", line 5, in <module>
    host = argv[1]
IndexError: list index out of range

Process finished with exit code 1

以下是示例解决方案代码:

import sys, time
from socket import *

argv = sys.argv
host = argv[1]
port = argv[2]
timeout = 1  # in second

clientsocket = socket(AF_INET, SOCK_DGRAM)
clientsocket.settimeout(timeout)
port = int(port)
ptime = 0

while ptime < 10:
    ptime += 1
    data = "Ping " + str(ptime) + " " + time.asctime()

try:
    RTTb = time.time()
    clientsocket.sendto(data, (host, port))
    message, address = clientsocket.recvfrom(1024)
    RTTa = time.time()
    print "Reply from " + address[0] + ": " + message
    print "RTT: " + str(RTTa - RTTb)
except:
    print "Request timed out."
    continue

clientsocket.close()

有关正在发生的事情的任何想法?我不明白为什么这不起作用。

1 个答案:

答案 0 :(得分:0)

你没有提到你是如何调用该程序的,但我猜它是py UDPClient.py而不是像py UDPClient.py foo bar这样的东西。程序名UDPClient.pysys.argv中的第0个元素。您添加的第一个参数是第一个元素,依此类推。