I have a folder called Command
where I keep a script suma
with the following code:
def suma_1(a, b):
return a+b
and I want to call it from a script in the same folder as Command
this way:
import os
print(os.path.pardir)
import Command
print(Command.suma.suma_1(1, 3))
I included os
it as an example at the top, because that's the way I want to import it. The problem is that it throws me an error warning that it does not exist suma
inCommando
..
Traceback (most recent call last):
File "c:/Users/joaqu/OneDrive/Escritorio/Informatica/ZZZ_CosasImportantes/Python/Importan/Terminal/prueba3.py", line 5, in <module>
print(Command.suma.suma_1(1, 3))
AttributeError: module 'Command' has no attribute 'suma'
Can I somehow import it without necessarily typing the script name?
I also tried with from Command import *
but it didn't work
You are really trying to import a package, not a module. Before Python 3.3 (regular packages only) it was necessary to add an
__init__.py
empty file to the package directory for Python to treat it as such. As of Python 3.3 (introduction of namespace packages) you don't need to do this explicitly ( Implicit Namespace Packages ) for Python to consider it as a package.Since I assume you use Python >= 3.3, Python already treats it
Command
as a package. The real problem is that when you importCommand
, the interpreter searches the directories in PYTHONPATH until it finds the directory but it doesn't scan that directory recursively and automatically imports all the .py files it finds. That is,suma.py
it is not imported.You have several options:
Without making use of the file
__init__.py
(namespace package) or using an__init__.py
empty file (regular package):O well:
Making use of a file
__init__.py
with content:Create a file called
__init__.py
insideCommand
and add the line:Now you can import just like you did in your code:
The file
__init__.py
is executed implicitly, and the objects defined in it are bound to names in the package namespace.