【发布时间】:2013-12-09 19:32:28
【问题描述】:
我有以下运行良好的 python 代码:
try:
with urlopen("http://my.domain.com/get.php?id=" + id) as response:
print("Has content" if response.read(1) else "Empty - no content")
except:
print("URL Error has occurred")
但我正在尝试将 try 中的 if else 语句更改为如下所示:这样我就可以运行额外的代码,而不仅仅是打印一条消息
try:
with urlopen("http://my.domain.com/get.php?id=" + id) as response:
if response.read(1):
print("Has content")
else:
print("Empty - no content")
except:
print("URL Error has occurred")
但是上面的不行,给出一个与缩进相关的错误
有什么想法吗?
【问题讨论】:
-
尝试删除 try-except 块并运行 try: 语句后面的代码。然后你会看到有什么问题。
-
你错过了围绕“有内容”的引号
-
另外,定义
not working -
这就是为什么你应该只捕获最窄的异常,即
URLError。 -
另外你应该把你的 if else 语句写在一行上。它将提高可读性
标签: python if-statement urlopen