查找 'fibo.py' 规范时出错(<class 'AttributeError'>:'module' 对象没有属性 '__path__') [英] Error while finding spec for 'fibo.py' (<class 'AttributeError'>: 'module' object has no attribute '__path__')
问题描述
我在 fibo.py
文件中有一个模块,它具有以下功能 -
I have a module in a fibo.py
file which has the following functions -
#fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
现在当我从 cli python3 运行模块时 -
Now when I run the module from the cli python3 as -
> python3 -m fibo.py
我收到错误
Error while finding spec for 'fibo.py' (<class 'AttributeError'>:
'module' object has no attribute '__path__')
__path__
变量具有当前目录.我不知道如何解决这个问题.
The __path__
variable has has the current dir . I am not sure how to fix this.
推荐答案
有两种方法可以运行 Python 3 脚本.
There are two ways you can run a Python 3 script.
python fibo.py
:参数是.py
文件的名称.点是文件名的一部分.python -m fibo
:参数是 Python 模块的名称,不带.py
.点表示包裹;fibo.py
表示fibo
包中的模块py
."
python fibo.py
: The argument is the name of the.py
file. Dots are part of the filename.python -m fibo
: The argument is the name of a Python module, without.py
. Dots indicate packages;fibo.py
means "the modulepy
in the packagefibo
."
对于像您这样的简单脚本来说,这是一个小小的区别.但是对于更大或更复杂的事情,它对 import
语句的行为有重要影响:
This is a small distinction for a simple script like yours. But for something bigger or more complex, it has an important effect on the behavior of the import
statement:
- 第一种形式将导致
import
搜索.py
文件所在的目录(然后搜索各种其他位置,包括标准库;参见sys.path
获取完整列表. - 第二种形式将使
import
搜索 当前 目录(然后是其他各种位置).
- The first form will cause
import
to search the directory where the.py
file lives (and then search various other places including the standard library; seesys.path
for a full list). - The second form will make
import
search the current directory (and then various other places).
因此,在 Python 3 下,大多数涉及包的设置(而不仅仅是目录中的松散模块)都需要第二种形式,因为脚本的父包可能无法在第一种形式下导入,即可能会导致事情破裂.
For this reason, under Python 3, the second form is required for most setups which involve packages (rather than just loose modules in a directory), since the parent package of the script may not be importable under the first form, which can cause things to break.
但是对于像这样的简单脚本,任何一种形式都可以.
But for a simple script like this, either form is fine.
这篇关于查找 'fibo.py' 规范时出错(<class 'AttributeError'>:'module' 对象没有属性 '__path__')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!