Search code examples
pythonbooggie

How can I access an external python module from a script in booggie 2?


This is a question for users of the graph transformation tool booggie:

In a script, is there a way to import an external python module in an arbitrary .py-file and use it like a regular python module within a script?


Solution

  • It's good practice to write a setEnvironment-script that adds required directories in the Python environment. As the location of the directories might vary from different computers, it's helpful to add a computer-name-switch.

    The script looks like this:

    def setEnvironment():
    """ GrGenSignature:  setEnvironment(): boolean     """
    
    import sys
    import os
    
    # Asking your computer for its name
    computer_name = os.getenv("COMPUTERNAME")   
    
    # Define path for PC1. That's where your modules are.
    # Make sure to use two backslashes!
    if computer_name == "PC1":
        source_path = "D:\\path\\to\\your\\project\\source" 
    
    # Add src folder to python enironment
    sys.path += [ os.path.join(source_path) ]
    
    
    # For those who want some info during the transformation
    print(("----------- Setting the environment for your project -----------"))
    print("This is computer:" + computer_name)
    print("Source path: " + str(source_path))
    print("----------------------------------------------------------------------")
    

    Now, you can import in any rule the modules, i.e. .py-files, in *source_path*. Make sure that you import within the script such that the import is done after the path is added. If you want to continue coding in your python module you can make sure to always get the latest version if you always reload the module. Hence in any script you can add this (assuming myHelper.py lies in the source path):

    import myHelper
    reload(myHelper)