Let’s say I have a python script called my_module.py in the location ~/junk/my_test/script/lib/. The my_module.py has a very trivial function called my_print() which just prints “Hello World”. The script looks like below:
def my_print():
        print "Hi there"

my_print()
Now I have another python script called my_another_python_script.py at the location /home/vbhadra/python_test_scripts/import_module. I want to call the function my_print() written in ~/junk/my_test/script/lib/my_module.py. The following is a easy way of doing it. This is python 3.x and hasn’t been tested in python 2.x or any other version. Follow the below code snippet:
import os
import sys

MY_IMPORT_DIR='~/junk/my_test/script/lib'

sys.path.append(os.path.expanduser(MY_IMPORT_DIR))

import my_module

def main():
        my_module.my_print()

if __name__=="__main()__":
        main()
Run the my_another_python_script.py as below: python my_another_python_script.py and you should see the below output: “Hello world”

Discover more from Tech For Talk

Subscribe to get the latest posts sent to your email.

Leave a Reply