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.
This commit is contained in:
Peter J. Holzer 2023-08-18 12:00:30 +02:00
parent 7de842141d
commit c406d13ce8
1 changed files with 4 additions and 1 deletions

View File

@ -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)