Created
January 3, 2021 21:13
-
-
Save arne-cl/e20357042bf87d02638d8bab3780cdc6 to your computer and use it in GitHub Desktop.
Python3: write to file if filename is given as argument, else write to 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
import argparse | |
import datetime | |
import sys | |
""" | |
This script writes the current timestamp to the file given a cli argument. | |
If no filename is given, the timestamp is written to stdout. | |
""" | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument('output_file', nargs='?', default=sys.stdout) | |
args = parser.parse_args() | |
timestamp = datetime.datetime.now() | |
if isinstance(args.output_file, str): # write to file | |
with open(args.output_file, 'w') as output_file: | |
print(timestamp, file=output_file) | |
else: # write to STDOUT | |
print(timestamp, file=args.output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Caveat: print(some_string, file=output_file) appends a newline at the end of the file!
Alternative: use output_file.write(some_string)