Skip to content

Instantly share code, notes, and snippets.

@ezr
Created August 29, 2021 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezr/8b035cdd377f20c89a65132a41a6cd23 to your computer and use it in GitHub Desktop.
Save ezr/8b035cdd377f20c89a65132a41a6cd23 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# argv[1] is the path to a configuration file
# the config file is a CSV file of the form date,path,message. EG:
# 03-03-2022,/home/user/py/remind/f,remember to do a backup
# 10-22-2021,/home/user/.motd,get tickets for Dune
from datetime import datetime
import os
import re
import sys
def main():
data = read_file(sys.argv[1])
# write back lines that we don't take action on to conf_output
conf_output = open(sys.argv[1], "w")
valid_line = re.compile('\d\d-\d\d-\d{4},.+,.+')
data = filter(valid_line.match, data)
for row in data:
fields = row.split(",", 2)
# >>> "05-15-2021,/home/user/motd,steal the vase, Indy!".split(',', 2)
# ['05-15-2021', '/home/user/motd', 'steal the vase, Indy!']
# note: a comma in the path will cause a bug
date_string, file, message = fields[0], fields[1], fields[2]
dt = datetime.strptime(date_string, "%m-%d-%Y")
if datetime.now().date() >= dt.date():
try:
append(message, file)
except Exception as e:
print("[!] caught an error while appending:", e)
print("[!] line that errored:", row)
conf_output.write(row)
else:
conf_output.write(row)
# if we crash before this point we lose the config data
conf_output.close()
def append(message, file):
file = file.replace("~", os.getenv("HOME"))
# we should test whether file is already open
f = open(file, "a")
if not message.endswith("\n"):
message = message + "\n"
f.write(message)
f.close()
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
if __name__ == '__main__':
main()
@ezr
Copy link
Author

ezr commented Aug 29, 2021

Run daily with systemd:

# /home/user/.config/systemd/user/append-at.service
[Unit]
Description=Run append-at script (add text to files on date)
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/home/user/bin/append-at.py /home/user/py/remind/append-at.conf

[Install]
WantedBy=multi-user.target
# /home/user/.config/systemd/user/append-at.timer
[Unit] 
Description=when to run append-at.py

[Timer]
Unit=append-at.service
OnCalendar=daily
Persistent=True

[Install]
WantedBy=basic.target

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment