Created
October 16, 2018 22:17
-
-
Save yanxurui/64d71ade56e9769ea75de77c29d29e08 to your computer and use it in GitHub Desktop.
a decorator to run a module and capture stdin/stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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