# Run script through Python without polluting namespace?

How can I use the Python API to run a Python script, exactly as if it were either opened with .use_module=True or run with or bpy.ops.text.run_script()?

I don't think the the existing answers are about the same question, because I think the use of exec() will necessarily pollute the namespace/globals/locals it's given, likely clobbering existing names. It also seems to have trouble with imports.

Things I've tried:

• exec(compile(), {}, {}): Doesn't handle imports of external modules correctly.

• Text.as_module() (followed by .register()): Doesn't set __file__ correctly.

• ops.script.reload(): Doesn't seem to actually run user scripts.

• Helo, are you running scripts from the command line ? Jun 7 '21 at 6:23
• @Gorgious I'm actually running them from another script, hence why clobbering globals() is unacceptable. For now I'm just switching the context area type to use ops.text.run_script(), but that's a bit dirty, so hopefully a better solution is possible. Jun 7 '21 at 14:59