Reputation: 350
I'm using python 2.7 in a linux environment and I'm having trouble importing a .py file under certain conditions. My directory-tree is as follows:
/mainFolder
executable.py
/Folder
input_file.py
executable.py
imports input_file.py
with the line __import__('input_file')
When I am in the folder mainFolder/Folder
and I run ../executable.py
I get the output: ImportError: No module named input_file
And when I move input_file.py
into mainFolder
it works. From looking at it I'm under the impression that input_file.py
isn't in python's path and I know how to fix that.
I'm under the impression though that it should work as is, as this is code that is from a github repository and presumably works on the author's computer, but this is apparently not the case.
Is there a setting I can change so I don't have to do something like sys.path.append(0,'mainFolder/Folder')
?
Upvotes: 0
Views: 7056
Reputation: 2907
"Packages" in python are identified by a file called
__init__.py
in the root of this package folder.
In this case, your tree should appears like:
/mainFolder
executable.py
/Folder
**__init__.py**
input_file.py
In this case, if you want import module: input_file as a module, you can declare in executable:
from Folder import input_file
or even
from Folder.input_file import *
from Folder import *
As alternative and following explanation found in this response, I implemented an example for your directory structure:
executable.py
file content:
Folder = __import__('Folder.input_file')
print(Folder.input_file.summm(1,2))
input_file.py
file content:
def summm(a, b):
return a+b
It is ugly, but was the to build an example following your original structure. In this case, it is not ncessary to add __init__.py
file inside Folder
folder.
Upvotes: 3
Reputation: 280
You can easily fix it
import Folder.input_file
or
__import__('Folder.input_file')
Where Folder
is the name of the folder input_file.py
is in.
Upvotes: 0