从教科书运行参数脚本时出错

时间:2015-02-07 21:54:45

标签: python typeerror traceback

我有一个Python初学者编码类。我们正在使用的书是#34; Coding for Penetration Testers Building Better Tools"。在第二章中,我们开始创建Python脚本,我似乎无法弄清楚这个脚本有什么问题我应该从书中重新输入。见下文。

import httplib, sys


if len(sys.argv) < 3:
    sys.exit("Usage " + sys.argv[0] + " <hostname> <port>\n")

host = sys.argv[1]
port = sys.argv[2]

client = httplib.HTTPConnection(host,port)
client.request("GET","/")
resp = client.getresponse()
client.close()

if resp.status == 200:
    print host + " : OK"
    sys.exit()

print host + " : DOWN! (" + resp.status + " , " + resp.reason + ")"

运行代码后,我在第20行(最后一条打印行)上收到错误,说明:

selmer@ubuntu:~$ python /home/selmer/Desktop/scripts/arguments.py google.com 80
Traceback (most recent call last):
  File "/home/selmer/Desktop/scripts/arguments.py", line 20, in <module>
    print host + " : DOWN! (" + resp.status + " , " + resp.reason + ")"
TypeError: cannot concatenate 'str' and 'int' objects

所有代码都在Ubuntu 14.04中在带有Konsole的VM中运行,并在Gedit中创建。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

从以下位置替换打印行:

print host + " : DOWN! (" + resp.status + " , " + resp.reason + ")"

使用:

print '%s DOWN! (%d, %s)' % (host, resp.status, resp.reason)

原始行尝试将一个int(resp.status)附加到字符串,如错误消息所示。