Run python script with other python script in same Blender file

How do I get a python script (“py1.py”) to run another python script (“py2.py”) in the same blender file? (i.e., both are internal text files/I do not want to have to have the whole directory path to run them.)

For example: say py2.py is

import bpy

print(“Hello world!”)

 If I have that open in the text editor, a simple "alt+p" prints "Hello world!" to the console.

But how do I get another script to do what “alt+p” on the active text object does?

Is it possible to write a function that takes a simple string as input, (in this case, just “py2.py”) and runs the script with that filename? I do not want to have to hardcode in the name of the file to be run.

edit: Got it!

A very simple py1.py:

import bpy
filename = “py2.py”
exec(bpy.data.texts[filename].as_string())

1 Like