Issue
Import python from different folder without using .py extension
Below is my python script (feed_prg) that calls the python script (distribute)
Please note that my script are at different location
feed_prg
is at location /opt/callscript
#!/usr/bin/env python
import sys
sys.dont_write_bytecode = True
sys.path.append('/home/username')
import distribute
# Main method start execution
def main(argv):
something = 'some'
distribute.feed(something)
if __name__ == "__main__":
main(sys.argv[1:])
distribute
is at location /home/username
#!/usr/bin/env python
import sys
def feed(something):
print something
def main():
something= "some"
feed(something)
if __name__ == "__main__":
main()
I am seeing the below error while executing ./feed_prg , and only when my distribute filename is just distribute and not distribute.py
Traceback (most recent call last):
File "./feed_prg", line XX, in <module>
import distribute
ImportError: No module named distribute
the distribute also has the execute privilege, as below
-rwxr-xr-x 1 username username 3028 Dec 16 21:05 distribute
How can I fix this. ? Any inputs will be helpful
Thanks !
Solution
It is not possible to do this using import
directly. It's best to simply rename the file to .py
That being said, it's possible to load the module into a variable using importlib
or imp
depending on your Python version.
Given the following file at path ./distribute
(relative to where python is run):
# distribute
print("Imported!")
a_var = 5
Python 2
# python2import
from imp import load_source
distribute = load_source("distribute", "./distribute")
print(distribute.a_var)
Usage:
$ python python2import
Imported!
5
Python 3
#python3import
from importlib.machinery import SourceFileLoader
distribute = SourceFileLoader("distribute", "./distribute").load_module()
print(distribute.a_var)
Usage:
$ python3 python3import
Imported!
5
Answered By - ParkerD
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.