Published on 2020-10-22, by Javed Shaikh
This sounds very funny but how can you let your team know that you are always online during work from home and doing your important stuffs 🙂. Here I will show how we can write a Python script with just few lines of code to keep our computer awake all the time. In this post, we are going to write a CLI script to keep our computer awake.
This script will take number of minutes as input and will keep right clicking every minute until it reaches the input time. We can add additional code to shutdown or restart the system once it reaches the countdown. It will also log the current system time in a text file and takes screenshot of the system before shutting down 🙂.
So what this CLI script will do?
1. Takes number of minutes (stop_time) as input (No. of minutes computer will awake) In a loop perform these after initiating a counter to 0
2. Save the logs of system
3. Take screenshot
4. Shutdown, Restart or do nothing if no action is provided by user
Well with this script you can pretend to be working and will always be online 😁 but in real you are going to learn few interesting things like
First of all lets import few libraries that we are going to use.
1import argparse
2import pyautogui
3import time
4import os
5
Why we are using these libraries?
Now lets write a new function named timer which will take two inputs i.e. input time or stop time and action to be performed. Please note that the input time is a integer variable which is number of minutes to keep our computer active
1def timer(stop_time, action):
2 counter = 0
3
Above we have defined a new function timer and initialized a counter to 0 Next we are going to start a loop until counter reaches the stop_time.
1 while stop_time > counter:
2 counter = counter + 1
3
Above code will execute and end within a moment but we want to keep system active for stop_time. To achieve that we are going to sleep for a minute and then do right click for each iteration
1 #Lets sleep for 60 seconds only
2 time.sleep(60)
3 pyautogui.click(button='right')
4
Lets understand what we did above.. sleep(n) is a special python function to delay or pause further execution of codes for n no of seconds. Here we are delaying execution for 60 seconds in each iteration. After 60 seconds we are doing mouse operation ('Right click') using Python library pyautogui
Next we are going to capture current system time using below instruction
1 #Save current date and time
2 timestamp = time.strftime('%d-%b-%Y_%H-%M-%S', time.localtime())
3
We used strftime function which convert local time to any readable format you want. Visit this link for more details on the format
Now lets write the log in a text file named "shutdown_logs.txt". Please note we are using mode a+ so that we can append the log in the same file for each script run. You need to update the location of the text file accordingly
1#Create a text log when system shuts down
2f = open('C:\\Users\\jaq\\Snapshot\\shutdown_logs.txt','a+')
3
Next we are going to write the log in the text file and close the file
1 f.write('Shutting down at {}'.format(timestamp))
2 f.close()
3
Take screenshot before shutting down
1#Take screenshot
2image_location = 'C:\\Users\\jaq\\Snapshot\\image_' + timestamp + '.jpeg'
3pyautogui.screenshot(image_location)
4
In the last part we are going to issue shutdown or restart command based on user inputs
1#Shutdown system or Restart
2if action in ['s', 'S']:
3 os.system("shutdown -s -f -t 0")
4if action in ['r', 'R']:
5 os.system("Shutdown -r -f -t 0")
6
If you have noticed 'action' is nothing but the function parameter in the very first line of code. Depending on the action parameter, we are issuing command to shutdown or restart using system() function of OS module.
With this , we are done with timer() function. Now we need to call it from our main function. So lets defined our function as below.
1if __name__ == "__main__":
2
3 parser = argparse.ArgumentParser()
4 parser.add_argument("-t", "--time", help="Enter time in minutes")
5 parser.add_argument("-a", "--action", help="want to shutdown?")
6
Lets understand what we did above. We are using argparse module to create our user friendly command line interface or CLI. In the first line we are creating ArgumentParser object and then in the next two lines we are adding two arguments for time and action input.
Next we will be calling timer function which we defined earlier. We will call the timer function only if we have the input time argument.
1 args = parser.parse_args()
2 if args.time:
3 timer(int(args.time), args.action)
4
That's it, we completed writing a CLI script in Python to keep our computer awake.
If you want to take a look at complete code, its available in my Github repository here https://github.com/jaqsparow/keep-system-active Though it sounds funny that we wrote a script to keep our system active or pretend that we are always online :), however in this post, we learned some important Python modules to do mouse operation, to write a file, to take screenshot and to shutdown or restart computer all with just few lines of code. We have also covered beautiful python CLI module argparse which is easy and efficient way of writing command line interface scripts.
Visit this Github page for the complete script click here
We are going to build a CLI app using Python to change desktop wallpaper every given number of minutes. Every wallpaper downloaded from internet will be unique and our app will change the wallpaper based on the time we set.
2020-10-27
There are many ways to monitor and set alerts for your web server using third party apps but they don't come with free, be it Pingdom or Amazon's CloudWatch. In this post I am going to show how we can write and setup our own alert tool with just few lines of code
2020-10-29
In this post we are going to see how we can use Python to find the size of any file and folder. We will check how many files we have inside a folder and how many of them are empty files and how to delete those empty files.
2020-10-26
Monitoring CPU and memory usage are one of the top todo checklist for a backend engineer. Sometimes you wont even notice when your server is down due to high CPU usage unless you login and manually check the system.
2020-11-04