Automating Your Digital Morning Routine with Python | by Lucas Soares | Towards Data Science

When you first get to your laptop/desktop in the morning you probably open quite a few applications. Doing this every day can get tiresome, so I wrote a script to automate the process of starting my day on my desktop, and in this tutorial I will show you how it works.
[Update 22/11/2021]
I made a video version of this article that you can check out on Youtube:
This script streamlines my daily routine right after booting my computer in the morning, handling a lot of the the basic manual tasks I have to get through before I can actually start working.
This routine involves processes like opening specific browser tabs, showing routine reminders, starting tracking scripts and more.
Let’s go through it line by line:
1. Import Dependencies
import webbrowserimport timeimport osimport subprocessfrom datetime import datetime
2. Write a notification function
def sendNotificationOnLinux(message):    subprocess.Popen(["notify-send", message])    return
Here I am using the built in library subprocess to call the notification system on my Linux machine and send a simple message. This is a neat way to automate talking to myself throughout the day.
This way I don't have to set up daily custom alarms for tasks I do every day. Below I also provide a similar Windows option:
def sendNotificationOnWindows(msg="", delay=2):    t = 0    notify = ToastNotifier()    while t < delay:        notify.show_toast("Notification",msg)        time.sleep(1)        t+=1
3. Write a continue day function
def continueDay():    cont = input("Press to continue")
Here I just wrapped the python built-in input() function to give it a more appropriate name, I use it do control the execution of the script line by line.
4. Log when I turn my computer on and off
os.system("bash /home/lucassoares/Desktop/projects/self_track/scripts/logSystemOnOff.sh")0
Here I am running a bash script to log when my computer was turned on and off for the last time to keep track of when I start working and when I stop. This bash script looks like this:
# logSystemOnOff.shecho "$(who -b)" >> path/to/file/systemOnOff.txt
5. Print reminders about trackers I am running
Now I leave a reminder for me that I am running tracking scripts for my keyboard and application windows.
print("Running keyfrequency and active window loggers with sudo")Run keyfrequency and active window loggers with sudo
These are run in parallel with this script using python’s multiprocessing package:
# call_Start_and_Logs.pyimport os                                                                       from multiprocessing import Pool                                                                                                                                                                                                                processes = ('/home/lucassoares/Desktop/automated/logWin.py',              '/home/lucassoares/Desktop/automated/logKeys.py',             '/home/lucassoares/Desktop/automated/startday.py')                                                                                                       def run_process(process):                                                                 os.system('python {}'.format(process))                                                                                                                                                                                                       pool = Pool(processes=3)  pool.map(run_process, processes)
Here I am running one python script to log all the keys I type on my keyboard (because I do a little bit of self-tracking on my linux machine which is a topic for another post) as well as the applications I use. The startday.pyscript mentioned above is the one we are discussing now.
6. Print reminder to start tracking focus
sendNotificationOnLinux("Turn on Focus")continueDay()
Here is a reminder for me to turn on focus, which is another script to track my focused time. Right now I am using a custom bash script called logFocus.sh to do it on the terminal. If you are curious this is the bash script:
logfile="/path/to/text/file/focus.txt"start="$(date +%s)"echo "Started logging focus"read stopecho "Stopped recording focus"echo "Calculating focus time"end="$(date +%s)"echo "$start $end" >> $logfile/path/to/python/executable/python /path/to/python/script/to/calculate/focused/time/calculateTodaysFocusTime.py
I recently found this terminal utility called timetrap that does this better so I might change it in the near future.
The python script to calculate and store focus time is the following:
from utils import loadFocusimport pandas as pdfrom datetime import datetimetoday = datetime.strftime(datetime.today(),format="%Y-%m-%d")timeStartsStamp,dateStartsStamp,durations = loadFocus()df = pd.DataFrame(dict(dates=dateStartsStamp, durations=durations))todayFocus = df[df["dates"]==today]["durations"].sum()print(todayFocus)
7. Spotify reminder
sendNotificationOnLinux("Turn on white noise")continueDay()
Here is another reminder to start Spotify and turn on white noise (yes I listen to white noise for a good portion of the day).
8. Open Google Calendar
# Google calendar eventssendNotificationOnLinux("Check your calendar")webbrowser.open("https://calendar.google.com/calendar/u/0/r/day")
This one is easy, I just open google calendar on my browser using python’s webbrowser module.
# Touch typing practiceprint("TYPE")os.system('"mlt random "0)-_=+[{]};:\'\|//?"') #pinky fingeros.system("mlt random 123456!@#$%^qwertasdfgzxcvbZXCVBASDFGQWERT~") #left handos.system("python /home/lucassoares/Desktop/automated/logTyping.py") #general practicecontinueDay()
This part is my daily touch typing practice routine. I use mltype, an awesome commandline tool, to improve typing on the command line! I wrote three variations of practice with this utility:
logtyping.py: Standard practice that samples a few lines of python scripts from a dataset I keep with modules and scripts that I find interesting
One that is focused on practicing my left hand (so just keys from the left hand on the keyboard)
Another one that is just for my pinky finger on my right hand which I found to be the bottleneck of my typing speed
The python script I call for my daily practice is this:
# logTyping.pyimport osimport pathlibimport randomimport pandas as pdfrom datetime import datetimeimport sysdef updateTypingPerformance(df,datedPerformance):    if "Unnamed: 0" in df.columns:        df.drop("Unnamed: 0", axis=1, inplace=True)    df.loc[len(df)] = datedPerformance    return dfdef typePractice(typingDataset):    files = list(typingDataset.iterdir())    file = random.choice(files)    f = open(file, "r")    numberOfLines = len(f.readlines())    print(file)    print(numberOfLines)    if numberOfLines>10:        numberOfLines=10    os.system(f"mlt file  --n-lines {numberOfLines} {file}")typingDatasetFolder = "path/to/folder/typingDataset"typingDataset = pathlib.Path(typingDatasetFolder)typingPerformance = "path/to/typing/performance/file/typingPerformance.csv"df = pd.read_csv(typingPerformance)typePractice(typingDataset)performance = []date = str(datetime.now())wpm = input("What was the wpm?")acc = input("Waht was the accuracy?")cont = input("Continue typing?")performance.append(date)performance.append(wpm)performance.append(acc)updateTypingPerformance(df,performance)while cont=="y":    performance = []    typePractice(typingDataset)    date = str(datetime.now())    wpm = input("What was the wpm?")acc = input("Waht was the accuracy?")performance.append(date)performance.append(wpm)performance.append(acc)updateTypingPerformance(df,performance)        cont = input("Continue typing?")if len(sys.argv)>1:    if sys.argv[1]=="plot":        df["wpm"].plot()        plt.show()
It’s basically setting up the training with the mlt command line tool and updating a .csv I keep with my touch typing performance.
9. Reminder for studying mandarin
print("MANDARIN")webbrowser.open("www.duolingo.com")continueDay()
This one is another self-explanatory one: I practice mandarin everyday so I automatically open it on my browser for my daily 10 minutes session.
10. Open project euler on browser for morning coding routine
print("CODE")webbrowser.open("https://projecteuler.net/archives")# start Anki
After practicing mandarin, I practice a bit of problem solving so I open project euler for my daily coding practice routine. I like just doing one exercise a day to warm up my brain.
I prefer to have some reminders on the terminal and some on the system’s notification pop-up, but this just comes down to personal taste, tweak it to your liking.
11. Checking communication channels
After I got done with the warm up part of my day, I like to start working by checking the basic communication outlets that I use, namely:
Slack (networking)
Teams (work)
Emails (work)
Whatsapp (social)
# teams, mail, slack, whatsappsendNotificationOnLinux("Open Mail, Teams, Slack and Whatsapp")os.system("teams")os.system("mailspring")os.system("slack")webbrowser.open("https://web.whatsapp.com/")
Once I am done checking these (I do it three times a day, one in the morning, one in the afternoon and one in the evening) I do a check on my medium stats to get a sense for how I am doing in the platform.
# mediumwebbrowser.open("https://medium.com/me/partner/dashboard")print("Check your stats on Medium")continueDay()
12. Final Reminders and finish
sendNotificationOnLinux(message="Leave an Ipython window Open")
This one is for me to remember to always leave an ipython window open so that I always have it there in case I need to do some quick scripting.
sendNotificationOnLinux(“Be grateful, no negative self-narratives and have a great day!”)
Here is a nice little daily reminder to keep me focused on what is important, always be grateful and avoid negative counterproductive self-narratives so I don’t get sidetracked.
The source code for this project can be found here.
I like these kind of automation scripts because they allow me to get my routines going faster by streamlining all of the manual processes, even if it is something as simple as opening tabs.
The point I want to make with this piece is to showcase the power of combining python with bash scripts to boost your productivity by automating the annoying manual tasks we have to get through every day.
I try to write these with a principle in mind of never doing something repeatedly if it can be automated.
If you are interested in learning bash scripting to optimize your development workflow, check out these courses from Udemy:
These are affiliate links, if you use them I get a small commission, cheers! :)
Bash Scripting and Shell Programming (Linux Command Line)
Linux Shell Scripting: A Project-Based Approach to Learning
If you liked this post connect with me on Twitter, LinkedIn and follow me on Medium. Thanks and see you next time! :)