Skip to content

Instantly share code, notes, and snippets.

@Musoye
Last active January 14, 2023 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Musoye/b08b1079d6bfa7263a3d34c73e566b74 to your computer and use it in GitHub Desktop.
Save Musoye/b08b1079d6bfa7263a3d34c73e566b74 to your computer and use it in GitHub Desktop.
import io
import sys
# Redirect stdout to a StringIO object/which, a file-like object
sys.stdout = io.StringIO()
# Print something (will be redirect to the StringIO object),this will be confirm with the end
print("This is a test", end='***')
# Get the contents of the StringIO object
output = sys.stdout.getvalue() #getvalue get the value written into StringIO object
# Reset stdout to its original value
sys.stdout= sys.__stdout__
#we can now write to stdout since stdout has been initialize to old stdout
# Print the captured output
print(output, end=' originalstdout\n')
#Boy will be printed since old standard output(sys.__stdout__) is reinitilaze to the changeable one(sys.stdout)
print('boy')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment