Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created October 8, 2019 04:12
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 louisswarren/292e125013e73a9683aa422ab95bd97a to your computer and use it in GitHub Desktop.
Save louisswarren/292e125013e73a9683aa422ab95bd97a to your computer and use it in GitHub Desktop.
Python open which uses a hyphen for stdin and stdout
import sys
def openstd(file, mode='r', *args, **kwargs):
if file == '-':
if 'r' in mode:
return sys.stdin
elif any(w in mode for w in 'wxa'):
return sys.stdout
else:
raise Exception("Mode not supported")
return open(file, mode, *args, **kwargs)
with openstd(sys.argv[1]) as infile, \
openstd(sys.argv[2], 'w') as outfile:
outfile.write("Got " + infile.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment