depot_tools: add create_temp_file.py

It takes text from stdin and dump the read text to a temp file.

Bug: 428193406
Change-Id: I268dc4905e157d619d1af7d0b96f711f224f39db
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/6789063
Reviewed-by: Gavin Mak <gavinmak@google.com>
Commit-Queue: Scott Lee <ddoman@chromium.org>
This commit is contained in:
Scott Lee
2025-07-28 11:27:45 -07:00
committed by LUCI CQ
parent 435e3b303e
commit 4fd484473c
2 changed files with 156 additions and 0 deletions

40
create_temp_file.py Executable file
View File

@@ -0,0 +1,40 @@
#!/usr/bin/env python3
import argparse
import os
import sys
import tempfile
def run(prefix=None, suffix=None):
""" Reads text from stdin, writes it to a temporary file.
The path of the temporary file is printed to stdout on success.
"""
try:
with tempfile.NamedTemporaryFile(mode='w+',
delete=False,
encoding='utf-8',
prefix=prefix,
suffix=suffix) as temp_file:
for line in sys.stdin:
temp_file.write(line)
temp_file.flush()
temp_file_path = temp_file.name
print(temp_file_path)
except Exception as e:
print(f"An error occurred: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Writes stdin to a temporary file and then print the path.",
)
parser.add_argument('--prefix',
help="Optional prefix for the temporary file name.")
parser.add_argument('--suffix',
help="Optional suffix for the temporary file name.")
args = parser.parse_args()
run(prefix=args.prefix, suffix=args.suffix)