Import modules into other scripts

Hi -

I’ve written lots of functions in a ‘.py’ file and want to import them into other Glyphs scripts, but I keep getting errors.
To illustrate, here’s a simple example: suppose I have a file called “functions.py” saved in the user scripts folder, that looks like this:

---------- start of functions.py ----------
#MenuTitle: functions

import GlyphsApp

def someFunction():
…for x in Glyphs.font.glyphs:
…print(x)
---------- end of script ----------

And I want to use “someFunction()” in another script, called “anotherScript.py”, also saved in the user scripts folder:

---------- start of anotherScript.py ----------
#MenuTitle: anotherScript

import functions

functions.someFunction()
---------- end of script ----------

If I try to run “anotherScript.py” from the Glyphs menu, I get this error:

NameError: global name ‘Glyphs’ is not defined

Any thoughts on how to set this up?

Is there also a way to have access to the contents of “functions.py” from within the macro panel?

Thanks for your help!

I tried it and had the same result. I look into it.

Thanks for investigating. I figured out a workaround for now where I add a parameter to the functions in “functions.py” that stands in place for “Glyphs” in the script.

In case it helps anyone else, here’s how I modified the example above:

---------- start of functions.py ----------
#MenuTitle: functions
#note that this file no longer has any reference to GlyphsApp.

def someFunction(GLYPHS_OBJECT):
…for x in GLYPHS_OBJECT.font.glyphs:
…print(x)
---------- end of script ----------

Then “anotherScript.py” would look like this:

---------- start of anotherScript.py ----------
#MenuTitle: anotherScript

import GlyphsApp

import functions

functions.someFunction(Glyphs)
---------- end of script ----------

It makes the code a bit more messy, but still gets the job done.

Also, not sure if this is related, but I’ve been having problems printing to the console from scripts being run from the menu. I think the problem arises when the print statements are in a file being imported into another script. The strange thing is that besides not printing the desired line, it also aborts the script (without error), and messes up printing of any kind (even directly from the macro panel) until relaunching the application. And even after relaunching, sometimes it takes a few attempts before print works again.