首页 > 解决方案 > 有没有办法在 python 中重复 try 和 except 块?(找不到目标时出现属性错误)

问题描述

我经常使用 SIMBAD 服务来查找天体的坐标。我想我会使用 python 自动化这个。我的第一种方法是使用 Selenium 并让它在 Safari 中运行。但是,事实证明这比手动操作要困难一些。然而,大约两天前,我发现了 astroquery 以及它是如何内置 SIMBAD 的。所以我想我会用那个。它确实有效,但它不断引发此属性错误,并且我所有修复它的尝试都导致了一个新错误。这是代码:(ps我正在使用astroquery库((astroquery.simbad))和一个文本格式化程序,丰富):

from rich import print
from astroquery.simbad import Simbad


def ask_for(prompt, error_msg=None, _type=None):
    """ While the desired prompt is not given, it repeats the prompt. """
    while True:
        inp = input(prompt).strip()
        if not inp:
            if error_msg:
                print(error_msg)
            continue

        if _type:
            try:
                inp = _type(inp)
            except ValueError:
                if error_msg:
                    print(error_msg)
                continue
        return inp


def simbad_query():
    not_target = True
    while not_target:
        try:
            print(
                '\nTo find the [blue]RA and Dec[/blue] of your target, please put it in here.')
            print("If your target can't be found, it will automatically redirect you to the website to put it in again.")
            target = ask_for('\nTarget name: ')
            query = Simbad.query_object(f'{target}')
            query.pprint()
        except AttributeError:
            print(
                '\nThe target you gave was [red]not found[/red]. Please try again.')
            print(
                '\nTo find the [blue]RA and Dec[/blue] of your target, please put it in here.')
            print("If your target can't be found, it will automatically redirect you to the website to put it in again.")
            target = ask_for('\nTarget name: ')
            query = Simbad.query_object(f'{target}')
            query.pprint()

标签: pythonmacos

解决方案


推荐阅读