How to append multiple Paths to PYTHONPATH programmatically

kamal picture kamal · May 15, 2012 · Viewed 15k times · Source

I have 4 directories:

/home/user/test1
/home/user/test2
/home/user/test3
/home/user/test4

I have another directory with tests

/home/user/testing

having the file testall.py

ow, how can I append PATHS, for test1 thru test4 to PYTHONPATH so that I can access the files under test1 thru 4.

btw, test1 thru 4 have multiple directories under them where the python files are located.

I tried:

import sys
import os
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0,os.path.join(PROJECT_ROOT,"test1"))
sys.path.insert(1,os.path.join(PROJECT_ROOT,"test2"))
sys.path.insert(2,os.path.join(PROJECT_ROOT,"test3"))
sys.path.insert(3,os.path.join(PROJECT_ROOT,"test4"))

did not seem to work

also:

import sys
sys.path.append('/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4')
from test1.common.api import GenericAPI

did not work.

basically: from test1.common.api import GenericAPI should work

Answer

An Se picture An Se · May 30, 2019

sys.path.append('/home/user/test1','/home/user/test2', ...) does not work because append() function can take only 1 argument.

What you could use instead is:

import sys
sys.path += ['/home/user/test1','/home/user/test2','/home/user/test3','/home/kahmed/test4']