【问题标题】:Python if else within a try and except [closed]Python if else in try and except [关闭]
【发布时间】: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


【解决方案1】:

您可以将异常放入变量并打印出来

except Exception as e:
    print("Error has occurred", e)

如果您缩进看起来像原始问题,那么这可能是您的问题 - 将制表符与空格混合

【讨论】:

  • 你是对的,我认为标签中有一些空格,所以我把所有东西都拿出来重新缩进,它解决了问题。
【解决方案2】:

您应该使用不同的try 块分隔可能发生异常的不同区域。

具体来说,不要用try 块包围with,而是使用contextlib 模块来处理这些细节。这是直接来自PEP 343,示例6:

from contextlib import contextmanager

@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except (IOError, err):
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()   

with opened_w_error('/tmp/file.txt', 'a') as (f, err):
    if err:
        print ("IOError:", err)
    else:
        f.write("guido::0:0::/:/bin/sh\n")   

【讨论】:

    【解决方案3】:

    您在第一个 if 中缺少引号。应该是

    if response.read(1):
        print("Has content")
    

    【讨论】:

      【解决方案4】:

      您可以尝试使用 else 子句来运行您的代码

      来自http://docs.python.org/2/tutorial/errors.html

      try ... except 语句有一个可选的 else 子句,当 现在,必须遵循所有 except 子句。它对以下代码很有用 如果 try 子句没有引发异常,则必须执行。为了 示例:

      for arg in sys.argv[1:]:
          try:
              f = open(arg, 'r')
          except IOError:
              print 'cannot open', arg
          else:
              print arg, 'has', len(f.readlines()), 'lines'
              f.close()
      

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 1970-01-01
        • 2016-08-30
        • 2011-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多