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 json
def write_chunk(chunk, file):
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)
def write_chunk(chunk, fd):
seek = chunk["seek"]
data = base64.b64decode(chunk["chunk"])
os.lseek(fd, seek, os.SEEK_SET)
os.write(fd, data)
def create_path(path):
try:
file.seek(seek)
file.write(data)
if not os.path.exists(path):
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:
print(e)
sys.exit(1)
def main():
file = None
if len(sys.argv) != 2:
print("Invalid number of arguments.")
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:
try:
json_in = input()
@ -66,17 +65,13 @@ def main():
break
json_list = json_in.split("\n") # need to split in case writes happen faster than reads
for json_obj in json_list:
try:
obj_in = json.loads(json_obj)
write_chunk(obj_in, fd)
except Exception as e:
print(e)
log = open("/var/log/navigator.log", "w")
log.write(json_in)
log.close()
os.close(fd)
sys.exit(1)
write_chunk(obj_in, file)
if file:
file.close()
os.close(fd)
sys.exit(0)
if __name__ == "__main__":