How to import a python script within another python script

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”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s