Error finding specification for 'fibo.py' (<class 'AttributeError'>: object 'module' does not have attribute '__path__')

I have a module in the fibo.py file that 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 cli python3 as -

 > python3 -m fibo.py 

I get an error

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

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

+15
source share
3 answers

There are two ways to run the Python 3 script.

  • python fibo.py : The argument is the name of the .py file. Dots are part of the file name.
  • python -m fibo : The argument is the name of the Python module, without .py . Dots indicate packets; fibo.py means " py module in fibo package."

This is a slight difference for a simple script like yours. But for something larger or more complex, it has an important effect on the behavior of the import statement:

  • The first form will cause import to search for the directory in which the .py file lives (and then search elsewhere, including the standard library, see sys.path for a complete list).
  • The second form will do an import search in the current directory (and then in other places).

For this reason, Python 3 requires a second form for most installations that include packages (and not just free modules in the directory), since the parent script package may not be imported in the first form, which can cause things to break.

But for a simple script like this, any form is fine.

+63
source

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

0
source

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

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

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

0
source

Source: https://habr.com/ru/post/1245805/


All Articles