You are on page 1of 7

 

(https://anderfernandez.com/en/)

How to automate a Python script on Windows and Mac

Requirements for automating a Automating our Python scripts is vital in order to get the most out of them. For complex things,
 I would
Python script on Windows and Mac always recommend automating scripts in the cloud, as we saw in this post
(https://anderfernandez.com/en/blog/automate-python-script-google-cloud/) on how to automate a
Automate Python script on Windows
Automate Python script on Windows
Python script on Google Cloud.
Automate Python script on Mac  
(https://anderfernandez.com/en/)
Conclusions However, many times we don’t need the automation to be perfect. In those cases, it is enough to
automate our Python scripts locally. That is why today we are going to learn how to automate our Python
scripts locally, on Windows and Mac. Let’s do it! de apostar en Inkabet Perú (https://www.elprogreso.es/articulo/deporte-local-lugo/inkabet-peru-apuestas-vivo-bono-bienvenida-inkabet-app/202105271825201505309.html)

Requirements for automating a Python script on Windows and Mac


The first thing we will need to automate our Python script (whether on Windows or Mac) is to have a
Python script that is 100% autonomous. That is, if we run the script from beginning to end (1) it will not
return errors or it will be able to handle them and (2) it will generate the result that interests us.

In this case, as an example, I will automate a very simple script for an ETL process. Basically, the script (1)
extracts the position data of the airplanes in circulation from an API and (2) uploads that data to a
database that I have mounted on Heroku. This is usually a typical case when access to the API is limited
and we want to have access to our historical data, for example.

The Python script that we are going to automate on both Windows and Mac is the following:

import requests
import pandas as pd
from sqlalchemy import create_engine

url = "https://opensky-network.org/api/states/all"
response = requests.get(url)
data = response.json()
df = pd.DataFrame(data['states'])

columns = ['icao24','callsign','origin_country','time_position','last_contact', '

df.columns = columns

# We only get 20 results


df = df.iloc[0:20,:]
host = 'XXX-XX-XXX-XXX-XXX.eu-west-1.compute.amazonaws.com'db = "XXXXXXXXXXXXXX"
user = "XXXXXXXXXXXXXX"pasw = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
engine = create_engine('postgres://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
df.to_sql('flights', engine,if_exists='append')

As we can see, this script is self-executing. However, since it is a local automation, it must be taken into
account that our automation may fail one day. Therefore, I think it is good practice that our code is
resilient to failures. In this case, we would get it by:

1. Reading the last data date in the database.


2. Extracting data from the API from that date to the current date.

With these two small changes, we would make our code much better and we would have much fewer
problems once it is automated. In any case, as an example it serves us. So, once we have our code and it
meets the requirements to automate it, let’s see how to automate our Python script on Windows and
Mac!

Automate Python script on Windows


To automate a Python script on Windows, we have to follow two steps:

1. Create a bat file that executes our file in Python


2. Automate the execution of our bat file with Task Scheduler.

Create a bat file that executes our Python file


A bat file is a type of DOS file used to execute command lines in the Windows console (Windows

Prompt). To create this file we are simply have to create a text file with the following structure:
Ander Fernández Jauregui (https://www.linkedin.com/in/ander-fernandez/) | Aviso Legal (https://anderfernandez.com/legal/)
<path to Python.exe> <path to the Python script we want to automate>
 
(https://anderfernandez.com/en/)

If you don’t know in which folder you have Python, you can check it with the following code:

import sysprint(sys.executable)

C:\Users\Ander\anaconda3\python.exe

A personal recommendation is that you save all the scripts that you want to automate in a folder that you
are not going to move. Otherwise, it could be the case that you rename the folder or move it to another
location, causing the automation to break. In my case, I have saved the script to automate in a folder
called “Auomations”.

Anyway, my bat file looks like this:

Now, we must save this file as a .bat file. Likewise, it is advisable to give it a name that we can identify,
in my case, I usually give the same name as the Python file: automate_flights.bat .

Now that we have created the file, we will have to automate it using TaskScheduler.

Automate the execution of our bat file with Task Scheduler


To create our bat file with Task Scheduler, we must first access Task Scheduler or Task Scheduler and
create a new task, as follows:

In the first screen called “General” we must include a name and description of the task that we are going
to automate. This will help us when we want to pause or modify this task.


Now we must indicate from when and how many times we want our code to be executed. We can do this
by creating a trigger. To do this, simply go to the “Triggers” tab and click “New”.

Once there, a window like the following will appear:

The first question is when you want the code to run. Although it can be done when you log in or open an
application, the most common is that it runs on a schedule. Within the schedule, we can choose (1) how
often we want it to run, (2) since when and (3) how many times a day.

Also, in the advanced section we can further modify the trigger so that, for example, our Python script
runs every five minutes.

Once we have configured the trigger as we want, we simply have to click “OK”.

Now, we must indicate that our file .bat is executed. To do this, simply go to the “Actions” tab and add a
new action.

In the pop-up window that appears, inside the box “Program or scipt” we must choose the .bat file that
we have created previously:
Finally, in the “Conditions” tab we can choose how this automation should behave depending on the
power state of our computer.

In this tab, we can choose things like to run (or not) the automation depending on whether the computer
is plugged into the power, or, for example, if the computer must be turned on to run the automation.

These settings will depend on your situation, but they are undoubtedly important.

Once we have configured this screen, we can click “OK” and that’s it, our automated Python script on
Windows!

Now that we’ve seen how to automate our Python script on Windows, let’s see how to automate our
Python script, but this time on Mac. Let’s get to it!

Automate Python script on Mac


Automating our Python script on Mac is easier than doing it on Windows (in my opinion), although it
should be done by console.

In this case, we will automate our Python script using a cronjob. To create a cronjob, we must open the
terminal and execute the following command:
crontab -e

With this, a section will open where we must create, via terminal, our cronjob. By pressing the i key, we
will enter the edit mode. To do this, we must indicate the following:

Necessary aspects to automate a Python script on Mac

1. Recurrence with which the cronjob should be executed


We define this recurrence by means of a crontab expression, which is basically a text string where each
position indicates: the minute, the hour, the day of the month, the month and the day of the week in
which we want it to be execute, being the asterisk * the way to indicate any (as in a regular expression).

An automation that runs every day at 9am will look as follows: 0 9 * * *. On the other hand, an
automation that runs every day every minute will be: * * * * *. I know this can be tricky, so I would
recommend using tools like crontab guru (https://crontab.guru/) to make sure your cron date is correct.

2. Directory where the Python script you want to automate is located


To copy the path where the file is located, you just have to go to the folder where the file is located and
press Cmd-Opt-C . With this keyboard shortcut, you will have copied the folder address to the clipboard (
link (https://apple.stackexchange.com/questions/338898/how-to-copy-path-of-a-file-in -mac-os)).

Now, you just have to paste that address and delete the file name, since in this case we need the file
path, but without including the file name. In my case, for example, the path is the following: / Users /
afernandez / Desktop /.

3. Path where Python is installed


The easiest way to find out the path where Python is installed is simply by running the following code in
terminal:

which python

After running this command, we will simply have to copy and paste the path that appears to us.

4. Python script name


Copying the name of the Python script is not complex. Simply go to the path where the file is located,
press enter on it and copy the name that appears.

Creation of the cronjob to automate our Python script on Mac


Now that we have all our ingredients, the command that we will have to create our cronjob will have the
following form:

In my case, I want to automate the script to run every day every minute, so my command has the
following form:

# Automate Python script


* * * * * * cd /Users/afernandez/Desktop/ && /opt/anaconda3/bin/python automate_flig

So, we enter this in our contrabs tab and we will press the esc key to exit edit mode (remember that to
enter edit mode you must have pressed the i , as explained above).

With this we would have our crontab created. Now to exit the tab and return to the terminal, simply type
: wq and press enter.

Now that we are in the terminal, we can check if our script has been successfully automated. To do this,
you can check if the cronjob you have created appears in the computer’s cronjobs list. You can do this
with the following command:

crontab -l

In our case, we will see how the cronjob we just created appears:

We now have our automated Python script on Mac! Now, if you wanted to delete it, it would be as simple
as:

1. Enter the cronjobs editor, using the command crontab -e and enter the edit mode by pressing i.
2. Delete the text of the cronjob you want to delete.
3. Exit edit mode by pressing esc and exit edit mode by entering : wq and pressing enter .

Conclusions
In short, automating a Python script, whether on Windows or Mac, is very simple and can take your
scripts to the next level. I personally have saved a lot of work for myself and the clients I work for
through automations.

So, if there is any work you do on a routine basis, you no longer have an excuse to automate it and be
more efficient! 😉

This has been all in this post. I hope you liked it. If this is the case and you want to be aware of the posts
that I am uploading (I’ve already posted 42 posts, of which 22 are in Python), I recommend that you
subscribe. In any case, see you in the next post!

You might also like