Hi Tom, hi Eric,

thanks a lot for Eric's suggestion! This is very neat and works like a charm!

@Tom: In a "normal" python script importing code from another module in the same directory is actually not a problem. As far as I understand, that is because calling "python myScript.py" prepends myScript's directory to sys.path (see e.g. https://docs.python.org/3/library/sys.html#sys.path). With pymol this also works, which is how I got used to organising all my pymol scripts that way. I suppose opening a script with chimerax just doesn't prepend its directory to sys.path then and there is no simple way to change this?

Thanks a lot once more,
 
Maik


From: Eric Pettersen <pett@cgl.ucsf.edu>
Sent: Thursday, April 18, 2024 3:13:10 AM
To: Engeholm, Maik
Cc: chimerax-users@cgl.ucsf.edu
Subject: Re: [chimerax-users] import from local file in chimerax-python script
 
Hi Maik.
I don't know if this is the "correct" solution, but this code in myScript.py will put those class definitions (well, any global definitions in classDefinitions.py) into myScript.py's global namespace:

from os.path import join, dirname
with open(join(dirname(__file__), "classDefinitions.py")) as f:
        exec(f.read(), globals(), locals())

--Eric

Eric Pettersen
UCSF Computer Graphics Lab

On Apr 17, 2024, at 2:03 PM, Engeholm, Maik via ChimeraX-users <chimerax-users@cgl.ucsf.edu> wrote:

Hi there,

I'm running a python script either from within ChimeraX (with "open myScript.py") or from the command line (using "chimerax myScript.py"). As the script gets longer and longer, I would like to store some class definitions in a separate file (classDefinitions.py within the same directory as myScript.py) and then import those into the main script with some command like "from classDefinitions import testClass". This, however, gives me an "ModuleNotFoundError: No module named 'testClass'". What is the correct way to do this?

Any help would be much appreciated!

Cheers,

Maik 

_______________________________________________
ChimeraX-users mailing list -- chimerax-users@cgl.ucsf.edu
To unsubscribe send an email to chimerax-users-leave@cgl.ucsf.edu
Archives: https://mail.cgl.ucsf.edu/mailman/archives/list/chimerax-users@cgl.ucsf.edu/