【问题标题】:Error when running argument script from textbook从教科书运行参数脚本时出错
【发布时间】:2015-02-07 21:54:45
【问题描述】:

我有一个 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 行(最后一个打印行)出现错误:

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

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

【问题讨论】:

    标签: python typeerror traceback


    【解决方案1】:

    从以下位置替换打印行:

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

    与:

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

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

    【讨论】:

    • 那个编辑效果很好!非常感谢,这似乎很奇怪,这是我遇到的第二段代码似乎写错了。最后一个 if 语句写错了,我花了很长时间才得到解决。不管。你认为你能解释为什么会这样吗?我喜欢从错误中吸取教训:)
    • 如果您使用+ 构建字符串,则必须确保每个项目都是str。例如,foo = "a" + "b" + "c" 可以,但bar = "a" + 1 不行。您可以通过说bar = "a" + str(1)(或在您的情况下为str(resp.status))来纠正第二个问题。但我的首选选项是改用字符串格式 - 使用% 标记来构建字符串,例如%s for str 和%d对于 int。有很多关于如何在 Python 中使用字符串格式的页面 - 所以值得阅读一些示例。
    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 2020-11-08
    • 2014-07-23
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2015-01-31
    相关资源
    最近更新 更多