Skip to content

Instantly share code, notes, and snippets.

@yanxurui
Created October 16, 2018 22:17
Show Gist options
  • Save yanxurui/64d71ade56e9769ea75de77c29d29e08 to your computer and use it in GitHub Desktop.
Save yanxurui/64d71ade56e9769ea75de77c29d29e08 to your computer and use it in GitHub Desktop.
a decorator to run a module and capture stdin/stdout
def run(module_path):
# run a module
# capture standard input and output
def wrapper(input):
stream_in = StringIO(input)
stream_out = StringIO()
stdin_ = sys.stdin
stdout_ = sys.stdout
sys.stdin = stream_in
sys.stdout = stream_out
runpy.run_path(module_path)
sys.stdin = stdin_
sys.stdout = stdout_
return stream_out.getvalue()
wrapper.__name__ = module_path
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment