because why not
This commit is contained in:
74
files/sponge
74
files/sponge
@@ -1,25 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import time
|
||||
from argparse import ArgumentParser
|
||||
|
||||
# Set up options
|
||||
parser=ArgumentParser(description="Sponge file before writing output: grep foo file.txt | sponge file.txt",
|
||||
epilog="This tool is a modification from http://joeyh.name/code/moreutils/ with the same name.")
|
||||
parser.add_argument("-a",action="store_true",dest="append",default=False,
|
||||
help="Append to file instead of overwriting")
|
||||
parser.add_argument(type=str,dest="file",
|
||||
help="File to write to")
|
||||
options=parser.parse_args()
|
||||
|
||||
# Read data
|
||||
data=sys.stdin.read()
|
||||
class Verbose:
|
||||
def __init__(self):
|
||||
self.progress_chars = " ▏▎▍▌▋▊▉█"
|
||||
self.progress_n = 0
|
||||
self.ts = 0
|
||||
self.loops = 0
|
||||
|
||||
def next(self):
|
||||
if time.time() > self.ts + 0.1:
|
||||
s = (
|
||||
" "
|
||||
+ self.loops * self.progress_chars[-1]
|
||||
+ self.progress_chars[self.progress_n]
|
||||
+ "\r"
|
||||
)
|
||||
print(s, file=sys.stderr, end="")
|
||||
self.progress_n = (1 + self.progress_n) % len(self.progress_chars)
|
||||
if self.progress_n == 0:
|
||||
self.loops += 1
|
||||
if self.loops >= 10:
|
||||
print(" " * 11 + "\r", file=sys.stderr, end="")
|
||||
self.loops = 0
|
||||
sys.stderr.flush()
|
||||
self.ts = time.time()
|
||||
|
||||
|
||||
# Set up options
|
||||
parser = ArgumentParser(
|
||||
description="Sponge file before writing output: grep foo file.txt | sponge file.txt",
|
||||
epilog="This tool is a modification from http://joeyh.name/code/moreutils/ with the same name.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-a",
|
||||
action="store_true",
|
||||
dest="append",
|
||||
default=False,
|
||||
help="Append to file instead of overwriting",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v", action="store_true", dest="verbose", default=False, help="Progress to stderr"
|
||||
)
|
||||
parser.add_argument(type=str, dest="file", help="File to write to")
|
||||
options = parser.parse_args()
|
||||
|
||||
|
||||
# choose mode
|
||||
mode="w"
|
||||
mode = "wb"
|
||||
if options.append:
|
||||
mode="a"
|
||||
mode = "ab"
|
||||
if options.verbose:
|
||||
v = Verbose()
|
||||
chunk_size = 1024 * 1024 * 1 # Mb
|
||||
|
||||
# Write the file
|
||||
writer=open(options.file, mode)
|
||||
writer.write(data)
|
||||
writer.close()
|
||||
with open(options.file, mode) as writer:
|
||||
while True:
|
||||
chunk = sys.stdin.buffer.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
if options.verbose:
|
||||
v.next()
|
||||
writer.write(chunk)
|
||||
|
||||
Reference in New Issue
Block a user