vendredi 10 juin 2016

Dynamically change sys.path of imported module [on hold]


I have the following three files:

  1. config.py
  2. /some/path/to/serverFolder/server.py
  3. /some/path/to/experimentFolder/experiment.py

The file config.py defines the locations of the other two files and imports server.py.

#file:config.py

import sys

experimentPath="/some/path/to/experimentFolder/"
serverPath="/some/path/to/serverFolder/"
sys.path.append(serverPath)

import server
server.importModules(experimentPath)

The file experiment.py just defines a class:

#file: experiment.py

class ExperimentClass:
    pass

The file server.py defines a class which inherits the class from experiment.py:

#file: server.py

import sys

def importModules(thisPath):
    sys.path.append(thisPath)
    import experiment
    return experiment


#experiment=importModules("/some/path/to/experimentFolder/")

class TestClass(experiment.ExperimentClass):
    pass

In the above programs, I get the error: NameError: global name 'experiment' is not defined, because I don't add experimentPath to the sys.path in the server.py file. If I uncomment the commented line in that file it works.

Ultimately, what I would like to be able to do would be to define the path to experiment.py (experimentPath) in the config.py file, and then be able to import experiment.py in the server.py file without explicitly defining experimentPath in the server.py file.

Question: Is it possible to add a path to the sys.path of a module before it is imported?

The reason I want to do this is server.py will be an unchanging file, but there will be several different versions of the config.py file, each which may have a different experimentPath. So ideally I would like to only have on


Aucun commentaire:

Enregistrer un commentaire