Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

python 3.x - Error while finding spec for 'fibo.py' (<class 'AttributeError'>: 'module' object has no attribute '__path__')

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

Now when I run the module from the cli python3 as -

> python3 -m fibo.py

I get the error

Error while finding spec for 'fibo.py' (<class 'AttributeError'>:
'module' object has no attribute '__path__')

The __path__ variable has has the current dir . I am not sure how to fix this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two ways you can run a Python 3 script.

  1. python fibo.py: The argument is the name of the .py file. Dots are part of the filename.
  2. python -m fibo: The argument is the name of a Python module, without .py. Dots indicate packages; fibo.py means "the module py in the package fibo."

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:

  1. 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; see sys.path for a full list).
  2. The second form will make import search the current directory (and then various other places).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...