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

妖精的绣舞 提交于 2019-11-27 00:43:33

问题


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.


回答1:


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.




回答2:


These are two different ways to run a python 3 script:

python fibo.py: The argument is the name of the .py file.

python -m fibo: The argument is the name of a Python module, without .py




回答3:


In addition to Kevin's answer: you should add path to your script folder to PYTHONPATH environment variable to make it work on some OS.



来源:https://stackoverflow.com/questions/36230492/error-while-finding-spec-for-fibo-py-class-attributeerror-module-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!