use os.open and os.write instead of regular file

This commit is contained in:
joshuaboud 2021-11-12 12:03:51 -04:00
parent 330ca90008
commit ee8c110203
No known key found for this signature in database
GPG Key ID: 17EFB59E2A8BF50E

View File

@ -31,34 +31,33 @@ import os
import sys import sys
import json import json
def write_chunk(chunk, file): def write_chunk(chunk, fd):
if not file:
path = sys.argv[1]
parent_path = os.path.dirname(path)
try:
if not os.path.exists(parent_path):
os.makedirs(parent_path, exist_ok=True)
elif os.path.isfile(parent_path):
print(parent_path + ": exists and is not a directory.")
sys.exit(1)
file = open(path, "wb")
except Exception as e:
print(e)
sys.exit(1)
seek = chunk["seek"] seek = chunk["seek"]
data = base64.b64decode(chunk["chunk"]) data = base64.b64decode(chunk["chunk"])
os.lseek(fd, seek, os.SEEK_SET)
os.write(fd, data)
def create_path(path):
try: try:
file.seek(seek) if not os.path.exists(path):
file.write(data) os.makedirs(path, exist_ok=True)
elif os.path.isfile(path):
print(path + ": exists and is not a directory.")
sys.exit(1)
except Exception as e: except Exception as e:
print(e) print(e)
sys.exit(1) sys.exit(1)
def main(): def main():
file = None
if len(sys.argv) != 2: if len(sys.argv) != 2:
print("Invalid number of arguments.") print("Invalid number of arguments.")
sys.exit(1) sys.exit(1)
fd = None
path = sys.argv[1]
parent_path = os.path.dirname(path)
create_path(parent_path)
try:
fd = os.open(sys.argv[1], os.O_WRONLY | os.O_TRUNC | os.O_CREAT)
while True: while True:
try: try:
json_in = input() json_in = input()
@ -66,17 +65,13 @@ def main():
break break
json_list = json_in.split("\n") # need to split in case writes happen faster than reads json_list = json_in.split("\n") # need to split in case writes happen faster than reads
for json_obj in json_list: for json_obj in json_list:
try:
obj_in = json.loads(json_obj) obj_in = json.loads(json_obj)
write_chunk(obj_in, fd)
except Exception as e: except Exception as e:
print(e) print(e)
log = open("/var/log/navigator.log", "w") os.close(fd)
log.write(json_in)
log.close()
sys.exit(1) sys.exit(1)
write_chunk(obj_in, file) os.close(fd)
if file:
file.close()
sys.exit(0) sys.exit(0)
if __name__ == "__main__": if __name__ == "__main__":