So I am executing come code:
python my_app.py > console.txt
So this allows me to generate a file on disk with all of the console print outs.
Then somewhere in the script I want to send the report in an e-mail. But whenever I do that I get a truncated version of the file. When the app closes the file has all of the information.
I tried this:
my_file = open('console.txt', 'r+', 1)
my_file.flush()
os.fsync(my_file.fileno())
my_file.close()
time.sleep(60)
filename = 'console.txt'
with open(filename, "r+", 1) as attachment:
print(attachment.readline(-20))
attachment.flush()
os.fsync(attachment.fileno())
time.sleep(60)
# Add file as application/octet-stream
# Email client can usually download this automatically as
# attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
attachment.close()
# # Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
"attachment; filename={}".format(filename),
)
# Add attachment to message and convert message to string
email.attach(part)
But still the file gets sent truncated. Any ideas or tips on how to flush everything to disk, my manual triggers dont work here :(
The code moves the stream position (or file pointer) in the readline(-20)
statement.
The file pointer needs to be moved back to the beginning of the file by calling attachment.read(0)
before being read again, if the code is to read the entire file.