Python if else 在 try 和 except 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20479065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:33:32  来源:igfitidea点击:

Python if else within a try and except

pythonif-statementurlopen

提问by John

I have the following python code that works well:

我有以下运行良好的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")

But I am trying to change the if else statement within the try to something like this: so that I can run extra code rather than just print a message

但是我试图将 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")

But the above is not working, giving an error related to indent

但以上不起作用,给出与缩进相关的错误

Any ideas what's wrong?

任何想法有什么问题?

采纳答案by John La Rooy

You can put the exception into a variable and print that too

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

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

If you indenting looks like the original question, then that may be your problem - mixing tabs with spaces

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

回答by AronVietti

You're missing quotation marks in the first if. Should be

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

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

回答by Pablo V.

You can try an else clause to run your code

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

From http://docs.python.org/2/tutorial/errors.html

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

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

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()

回答by dawg

You should separate different areas that an exception could occur with different tryblocks.

您应该将不同try块可能发生异常的不同区域分开。

Specifically, rather than surround withwith a tryblock, use the contextlibmodule to handle these details. This is straight out of PEP 343, example 6:

具体来说,不要withtry块包围,而是使用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")