0

I have a python file, with a function that I want to call in multiple places. But I want the file with the function to be in the home directory and not have to store it in every directory I want to use it. Is this possible?

For example lets say I have a py file called add.py, and it is in the home directory and its this

def add(b):
    a = 3
    print "ADDING %d + %d" % (a, b)
    return a + b

And then in a sub directory I want to call add, how could I do that, I know if there in the same directory I could do from a import add

But in my case the add function is more complex and I want to call it in a bunch of different places without having to store multiples of the file in each directory. I know I could use init.py, but what goes in the field?

Thanks

spen123
  • 3,464
  • 11
  • 39
  • 52
  • possible duplicate of [Python: Importing modules from parent folder](http://stackoverflow.com/questions/714063/python-importing-modules-from-parent-folder) – NightShadeQueen Jul 04 '15 at 03:17

1 Answers1

1

You can add the home directory to PYTHONPATH and then it would be possible to do from a import add.

To programmatically add a directory to PYTHONPATH , you can use sys.path.

Example -

import sys
sys.path.append('/path/to/home/directory')

After doing the above you would be able to directly import any scripts that exist in the home directory. Example if in home directory there is an a.py with add function, after above lines you would be able to do -

from a import add

Outside python, you can also set the PYTHONPATH environment variable to contain your home directory, and then you would be able to import any python scripts in the home directory directly (from anywhere) -

Example of setting the PYTHONPATH in bash -

export PYTHONPATH=$PYTHONPATH;/path/to/home/directory
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • OK, Im trying this on my comp, and right now a.py is in `/Doucments/py scripts` and b.py is in `/Doucments/py scripts/test` so I put `sys.path.append('/test')`, but it doesn't work, what should I be putting? Does it matter that there is a space in the file `py scripts`? – spen123 Jul 04 '15 at 03:22
  • 1
    You want to import `a` into `b` right? So shouldn't you be putting path of `a` ? Put complete path of `a` , not `b` – Anand S Kumar Jul 04 '15 at 03:24