In part two of this post I am going to discuss one of the biggest advantages of using Python: Automation. Automation is a powerful tool, because it enables us to solve a problem once and then have that solution continuously run, making it a permanent solution. I am going to walk through how I have automated a script that will send me an email everyday at 07:00 about the current weather in my location using a Python Daemon.
- First step is to make sure the script is correct with proper imports and scheduling code, as well as saved in the correct directory.
- Next, open a terminal (I used Linux) to begin the daemon process.
- After this, we have to navigate to the directory where the script is located. This will be done using the “cd” command.
- Example: cd python_scripts
- Now we will begin the process of running the script in the background. To do this, we will need to use the “nohup” command. “nohup” stands for “no hang up” which means that the command will execute even if the user is logged out at the time. The other commands we will use is “python” or “python3” (which I used), to run the script in that language. The last thing will be “&” which makes the script run in the background.
- Example: nohup python3 API_mailer.py &
That is a step by step process on how you are going to begin the process of using a python daemon to run your script in the background. Next, we are going to go over how to verify this process worked and that you did this correctly.
- Once again we will start this process by being in the terminal
- Next, we will type in “ps aux | grep name_of_script.py”
- This command will give you a litany of information after you type this in and hit enter. You will see:
- The user that did the command
- The process ID
- The CPU percentage that the script is taking up to run
- The memory percentage
- The virtual memory size in KBs
- The resident set size
- The terminal type
- The process state codes
- The time when the command was initiated
- The cumulative CPU time
- The actual command that initiated the process
- Example for this: python3 API_mailer.py
- This command will give you a litany of information after you type this in and hit enter. You will see:
After we verify that our script is working, the last thing we need to worry about is if we want to stop the script. To stop the script is simple, we will just need to use the kill command and one bit of information from when we verified if it was running.
- Use the same code that we used to verify the process
- “ps aux | grep name_of_script.py”
- Find the process ID in that list which will be the second bit of info
- Then, we will just type that process ID and the word kill
- Example: 53764 kill
- After this our process is no longer running in the background
This post explains how we are able to automate a script to run in the background, verify that daemon is running, and how to stop the daemon once we are finished with it.