Python ImportError: 无法导入 __init__.py 名称

9

我遇到了这个错误:

ImportError: cannot import name 'life_table' from 'cdc_life_tables' (C:\Users\tony\OneDrive\Documents\Retirement\retirement-mc-master\cdc_life_tables\__init__.py)

当我尝试运行此代码(retirement_mc.py)时:
from cdc_life_tables import life_table

__init__.py 是这样的

#!/usr/bin/env python
from cdc_life_tables import *

cdc_life_tables.py 包含 life_table,代码如下:

def life_table(state_abbrev, demographic_group):
  
    state_abbrev = state_abbrev.upper()

    try:
        state = abbrev2name[state_abbrev]
    except KeyError:
        raise ValueError('"{}" not a state abbreviation.'.format(state_abbrev))

    state = state.lower().replace(' ', '_')


    try:
        demographic_group = demographic_group.lower()
        if len(demographic_group) > 2:
           demographic_group = groups_long2short[demographic_group]
    except KeyError:
        raise ValueError('"{}" not a valid .'.format(demographic_group))
        
    s = '{}{}_{}.csv'.format(lt_dir, state, demographic_group)

    if os.path.exists(s):
        df = pd.read_csv(s)
    else:
        raise ValueError('{} not a demographic group for {}.'.format(demographic_group, state_abbrev))

    return df['qx']
       
if __name__ == '__main__':
    q = life_table('PA', 'wf')

我正在使用Spyder (Python 3.7)。

我有点困惑 - 你是在尝试从一个只包含全局导入的模块(init.py)中导入一个命名函数(life_table)吗?这里的“*”代表什么? - match
我正在使用 * 来从 cdc_life_tables 导入所有变量。 - Simone
你在哪里尝试执行它?那是该模块中的有效名称吗? - Kenny Ostrom
我认为这是一个有效的名称。我会在上面添加一些更多的信息,可能会有所帮助。 - Simone
2个回答

12

用这行代码:

from cdc_life_tables import *

你的程序包尝试从自身导入import *。你需要从当前包的cdc_life_tables子模块中导入import *,最简单的方法是使用相对导入:

from .cdc_life_tables import *

谢谢,我从_init_.py中删除了"from cdc_life_tables import *",然后重命名了路径中的第一个文件,接着使用了:from life_tables.cdc_life_tables import life_table。 - Simone

0

我的__init__.py文件看起来像这样

repo_root = os.path.abspath(os.path.dirname(__file__))
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

repo_root 上出现了这个错误。

更改为

modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
repo_root = os.path.abspath(os.path.dirname(__file__))

问题已解决。

真让人烦恼,为什么没有更多详细的错误信息呢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接