2013-12-09 61 views
-5

我有行之有效以下Python代码:的Python如果在try和除其他

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

但上面不工作,给人以缩进

任何想法有什么不对相关的错误?

+0

尝试删除try-except块并运行try:语句后面的代码。你会看到有什么问题。 – leeladam

+2

你错过了“有内容” – njzk2

+2

的引号,定义'not working' – njzk2

回答

1

你可以把异常到一个变量和打印太

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

如果缩进看起来像原来的问题,那可能是你的问题 - 混合标签与空间

+0

你是正确的有一些空间,我认为在标签中,所以我把所有的东西都拿出来,重新缩进,并解决了问题。 – John

0

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

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

你可以尝试else子句来运行代码

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

的尝试... except语句有一个可选的else子句,当被 目前,必须遵守除条款之外的所有条款如果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() 
0

你应该分开不同的区域,可能会发生异常与不同try块。

具体而言,而不是将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")