2015-02-07 55 views
0

我有一个Python的初学者编码类。我们正在使用的这本书是“编码渗透测试人员构建更好的工具”。在第二章的第二章中,我们开始创建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行(最后的打印线)的错误,指出:

[email protected]:~$ 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的虚拟机中运行,创造了Gedit的。任何帮助,将不胜感激!

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

与:

回答

0

从更换打印线

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

原线将尝试添加一个int(resp.status)为字符串,作为错误消息表示。

+0

该编辑工作完美!非常感谢你,这似乎很奇怪,这是我所遇到的第二部分代码,似乎写错了。最后一个有if语句写错了,花了我很长时间才得到解决。而不管。你认为你可以解释为什么这有效吗?我喜欢从错误中学习,我可以:) – 2015-02-07 22:38:36

+0

如果你使用'+'来构建一个字符串,你必须确保每个项目都是'str'。例如,'foo =“a”+“b”+“c”'可以,但是'bar =“a”+ 1“不是。你可以通过说'bar =“一个”+ str(1)'(或者在你的情况下用'str(resp.status)'来纠正第二种情况。但是我的首选选择是使用字符串格式 - 使用'%'标记来建立一个字符串,比如用'%s'表示str,用'int d'表示int。关于如何在Python中使用字符串格式 - 有很多页面 - 所以值得通读几个例子。 – jlb83 2015-02-09 09:06:28