I am trying to import one python script from another. I have a few common functions defined in one script and then lots of other scripts that want to import those functions. No classes, just functions.
The importing script needs to import from a relative path e.g. ../../SharedScripts/python/common.py
I then a have a few functions def f1(...) defined which I will call.
I found the imp module which seemed to be the right thing to use but I was unable to figure out the exact syntax that would work for my example.
Can someone suggest the correct code to use or the simplest approach if imp is not the right module?
SOLUTION from the answers below I was able to get this working…
projectKey = 'THOR'
# load the shared script relative to this script
sys.path.append(os.path.dirname(__file__) + '/../../SharedScripts/python')
import jira
jira.CheckJiraCommitMessage(sys.argv[1], sys.argv[2], projectKey)
Where I had an empty __init__.py and a jira.py in the SharedScripts/python directory with plain function definitions.
Why not adding
../../SharedScripts/python/to the python path? Then you could usecommon.pylike any other module:You can alternate the Python path through the system variable
PYTHONPATHor by manipulating it directly from python:sys.path.append("../../SharedScripts/python/")Please notice that it is probably wiser to work with absolute pathes… (The current directory of the app could change)
To get the absolute path could can call use the function
os.path.abspath:os.path.abspath('../../SharedScripts/python/')