我试图从控制台运行一个模块。我的目录结构如下:
我试图使用以下命令从problem_set_02
目录运行模块p_03_using_bisection_search.py
:
$ python3 p_03_using_bisection_search.py
p_03_using_bisection_search.py
中的代码是:
__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
文件,但它仍然不起作用。
我和你有同样的问题。我认为问题在于您在
in-package import
中使用了相对导入。您的目录中没有__init__.py
。所以,正如摩西在上面所回答的。我认为最核心的问题是当你用点输入时:
相当于:
其中
__main__
表示当前模块p_03_using_bisection_search.py
。简而言之,解释器不知道您的目录结构。
当解释器进入
p_03.py
时,脚本等于:并且
p_03_using_bisection_search
不包含任何名为p_02_paying_debt_off_in_a_year
的模块或实例。因此,我在不更改python环境贵重物品的情况下提出了一个更干净的解决方案(在查看了相对导入中requests的工作原理之后):
目录的主要结构是:
main.py
setup.py
——
problem_set_02/
----
__init__.py
----
p01.py
----
p02.py
----
p03.py
然后输入
__init__.py
:这里的
__main__
是__init__
,它正好指模块problem_set_02
。然后转到
main.py
:import problem_set_02
您还可以编写一个
setup.py
来将特定模块添加到环境中。尝试将其运行为:
python3 -m p_03_using_bisection_search
只需删除相对导入的点并执行以下操作:
相关问题 更多 >
编程相关推荐