我正在尝试从控制台运行一个模块。我的目录结构是这样的:

我试图运行模块p_03_using_bisection_search.py,从problem_set_02目录使用:

$ python3 p_03_using_bisection_search.py

p_03_using_bisection_search.pyis中的代码:

__author__ = 'm'


from .p_02_paying_debt_off_in_a_year import compute_balance_after


def compute_bounds(balance: float,
                   annual_interest_rate: float) -> (float, float):

    # there is code here, but I have omitted it to save space
    pass


def compute_lowest_payment(balance: float,
                           annual_interest_rate: float) -> float:

    # there is code here, but I have omitted it to save space
    pass    

def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(input('Enter the annual interest rate: '))

    lowest_payment = compute_lowest_payment(balance, annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

我正在导入p_02_paying_debt_off_in_a_year.py中的函数,其代码是:

__author__ = 'm'


def compute_balance(balance: float,
                    fixed_payment: float,
                    annual_interest_rate: float) -> float:

    # this is code that has been omitted
    pass


def compute_balance_after(balance: float,
                          fixed_payment: float,
                          annual_interest_rate: float,
                          months: int=12) -> float:

    # Omitted code
    pass


def compute_fixed_monthly_payment(balance: float,
                                  annual_interest_rate: float) -> float:

    # omitted code
    pass


def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(
        input('Enter the annual interest rate as a decimal: '))
    lowest_payment = compute_fixed_monthly_payment(balance,
                                                   annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

我得到以下错误:

ModuleNotFoundError: No module named '__main__.p_02_paying_debt_off_in_a_year'; '__main__' is not a package

我不知道如何解决这个问题。我已经尝试添加一个__init__.py文件,但它仍然不工作。


当前回答

试着运行它:

Python3 -m p_03_using_bisection_search

其他回答

如果你已经创建了目录和子目录,请遵循以下步骤,请记住所有目录必须有__init__.py才能被识别为目录。

在脚本中,包括import sys和sys. sys。path,您将能够看到Python可用的所有路径。您必须能够看到当前的工作目录。 现在导入子目录和你想要使用的模块,使用:import subdir.subdir.modulename as abc,现在你可以使用该模块中的方法。

作为一个例子,你可以在这张截图中看到,我有一个父目录和两个子目录,在第二个子目录下,我有模块CommonFunction。在右边,我的控制台显示在执行sys。路径,我可以看到我的工作目录。

试着运行它:

Python3 -m p_03_using_bisection_search

只需使用.py文件所在的主文件夹的名称。

from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after

简单地删除相对导入的点,然后执行:

from p_02_paying_debt_off_in_a_year import compute_balance_after

删除圆点并导入文件开头的absolute_import

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after