From c406d13ce80885dec5cf1e9d3883972174004331 Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Fri, 18 Aug 2023 12:00:30 +0200 Subject: [PATCH] Write to temp file and rename it This is safer and allows changing the shebang on existing files. It does require write access to the directory, but typically that's required for installing a file anyway. --- install-python | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/install-python b/install-python index b2fc46a..3497ca6 100755 --- a/install-python +++ b/install-python @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import argparse +import os import shutil import sys @@ -11,7 +12,8 @@ ap.add_argument("destination") args = ap.parse_args() with open(args.source) as inf: - with open(args.destination, "w") as outf: + tmp_dest = args.destination + "." + str(os.getpid()) + with open(tmp_dest, "w") as outf: first_line = inf.readline() if first_line.startswith("#!"): print("#!", sys.executable, file=outf) @@ -20,5 +22,6 @@ with open(args.source) as inf: outf.write(first_line) for line in inf: outf.write(line) + os.rename(tmp_dest, args.destination) shutil.copymode(args.source, args.destination)