Complete worked example
python
import contextlib
import io
import runpy
def inspect_example():
imported_output = io.StringIO()
with contextlib.redirect_stdout(imported_output):
namespace = runpy.run_path('task.py', run_name='owned_module')
script_output = io.StringIO()
with contextlib.redirect_stdout(script_output):
runpy.run_path('task.py', run_name='__main__')
return {'importOutput': imported_output.getvalue(),
'scriptOutput': script_output.getvalue(), 'value': namespace['report']()}- Reasoning
- The first run_path call uses owned_module as the namespace name and captures standard output. Report is available in the returned namespace, but the guarded print does not run. The second call uses __main__, so the same guard prints the report value.