我正试图从控制台运行一个模块。我的目录的结构是这样的。
我试图运行p_03_using_bisection_search.py
模块,从problem_set_02
目录中使用。
$ 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
中的一个函数,其代码是:{{43827605}}。
__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
。所以就像上面Moses回答的那样导入。
我认为核心问题是当你用点导入时。
from .p_02_paying_debt_off_in_a_year import compute_balance_after
相当于:
from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after
其中__main__指的是你当前的模块
p_03_using_bisection_search.py'。
简而言之,解释器不知道你的目录结构,。
当解释器进入p_03.py
时,脚本等同于。
from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after
并且p_03_using_bisection_search
不包含任何名为p_02_paying_debt_off_in_a_year
的模块或实例。
所以我想出了一个更简洁的解决方案,不需要改变python环境中的值(在查找了request在相对导入中的作用后)。
目录的主要架构是。
`main.py
setup.py
------__init__.py
。
------p01.py
------p02.py
------p03.py
然后在__init__.py
中写入。
from .p_02_paying_debt_off_in_a_year import compute_balance_after
这里的__main__就是
init,它正好指的是
problem_set_02`模块。
然后转到main.py
。
import problem_set_02
。
你也可以写一个setup.py
来添加特定的模块到环境中。
你好,请遵循以下步骤,你将解决这个问题。
如果你已经创建了目录和子目录,那么请按照以下步骤操作,请记住所有的目录必须有__init__.py
才能被识别为一个目录。
1.import sys
并运行sys.path
,你将能够看到所有正在被python搜索的路径,你必须能够看到你当前的工作目录。
2.2. 现在使用import命令导入子目录和你想使用的相应模块。import subdir.subdir.modulename as abc
,现在你可以使用该模块中的方法。
ScreenShotforSameIssue。
如你所见,在这个截图中,我有一个父目录和两个子目录,在第二个子目录下,我有模块==CommonFunction 你可以看到在执行sys.path后的右侧,我可以看到我的工作目录