Automation Scripts: A Comprehensive Guide
Upendra Prasad Mahto
Posted On: June 7, 2023
111364 Views
16 Min Read
In today’s era, we mainly focus on saving time and increasing efficiency; automation scripts play an important role. In this comprehensive guide, we will delve into the world of automation scripts and explore their extensive capabilities. However, before we embark on this journey, let’s take a moment to understand what automation scripts truly mean.
Automation scripts are essentially computer programs or sets of instructions written using scripting languages like Python, PHP, JavaScript, and others. Their primary purpose is to simplify and streamline repetitive tasks, enabling us to save valuable time and effort. Throughout this guide, we will dive deep into a carefully curated collection of highly effective automation scripts, each offering its unique set of benefits. Later, we will also look at some of the advanced automation techniques and real-world use cases of automation scripts.
So, without further ado, let’s kick off our exploration by diving into the concept of automation scripts and uncovering their advantages.
TABLE OF CONTENTS
- Understanding Automation Scripts
- Choosing the Right Automation Scripting Language
- Strengths and Weaknesses of Top Scripting Languages
- Top 12 Automation Scripts Worth Implementing
- Exploring Advanced Automation Techniques
- Real-World Use Cases of Automation Scripts
- Conclusion
- Frequently Asked Questions
Understanding Automation Scripts
As we discussed above, automation scripts are nothing but computer programs or instructions written in scripting languages like Python, JavaScript, etc., that are used to automate repetitive tasks. Automation scripts are designed to minimize human actions. It executes specific actions without manual involvement. It reduces time and energy so that the user can use it for more valuable and complex tasks. It also improves efficiency and accuracy.
Now, we will explore the advantages of automation across different domains, such as IT operations, data analysis, quality assurance, and software testing.
- IT Operations
Within this context, automation scripts play a fundamental role in identifying and resolving typical IT issues, such as cache clearance and system verification. Additionally, these scripts facilitate the automation of tasks like backups and system performance monitoring. - Data Analysis
When it comes to data analysis, automation scripts excel in collecting data from diverse sources and carrying out operations like data cleansing, filtering, and more. - Quality Assurance and Software Testing
Automation scripts play a vital role in automating software testing processes, including unit testing, regression testing, and performance testing. It ensures reliable and efficient testing cycles. It also enables the integration and deployment of software updates, automating build processes that ensure consistent delivery.
Choosing the Right Automation Scripting Language
There are many scripting languages used in the automation scripts, like – Python, PHP, Perl, VBScript, Jython, JavaScript, etc. Therefore, we need to choose the right automation scripting language. But before choosing, several factors need to be considered.
So let’s discuss some key considerations that help you to make an informed decision.
Ecosystem and Community Support
A strong ecosystem and active community can provide valuable resources, libraries, forums, and tutorials that help you to overcome challenges and learn from others’ experiences. For example- StackOverflow.
Platform Compatibility
Some scripting languages have better support or built-in features for specific platforms, so ensuring compatibility with your target environment is essential. For example- JavaScript works flawlessly on web browsers.
Performance and Execution Speed
Some compiled languages like C and C++ offer faster execution speeds than interpreted languages like Python. Therefore you may need to consider the execution speed and performance of the scripting languages.
Security Considerations
Depending on your use case, you may need to handle sensitive data or interact with security systems. Therefore, you have to ensure that the scripting language has powerful security features or can integrate with secure protocols.
Future Scalability and Extensibility
We need to consider the scalability and extensibility of the scripting language. We want to know if the chosen scripting language can accommodate growth and evolving automation needs.
Task Complexity and Requirements
Evaluate the complexity of the tasks you need to automate because some scripting languages, like Python, offer extensive libraries and frameworks that support a wide range of functionalities that makes them suitable for handling complex automation tasks.
Familiarity
If you are already familiar with a particular scripting language, choosing a language with your expertise may be more efficient. You can also choose a scripting language that is easier for you to acquire the necessary skills.
Strengths and Weaknesses of Top Scripting Languages
Let’s discuss some strengths and weaknesses of famous scripting languages like Python, JavaScript, and PowerShell.
Scripting LanguagesStrengthWeakness
Python |
|
|
JavaScript |
|
|
PowerShell |
|
|
We briefly looked at the strengths and weaknesses of some famous scripting languages, but the question that arises is, which scripting language should we use?
If we consider the ease of use, then Python stands out with its simplicity and readability, JavaScript’s web-centric focus makes it a natural choice for web-related automation tasks, and PowerShell excels in Windows system automation due to its deep integration with Microsoft technologies. In terms of community support, Python and JavaScript have large and active communities, while PowerShell benefits from a strong Windows-focused ecosystem. All three languages offer cross-platform compatibility to varying degrees, with Python being the most versatile in this regard.
Let’s see the top 12 automation scripts which are very useful. Please note that all of them are written in Python. You may choose a different language, like JavaScript, to do these tasks as well.
Top 12 Automation Scripts Worth Implementing
1. Move all the unwanted files from the desktop into a new folder.
In this particular illustration, we are relocating all the files to a newly created directory called “Everything.” Nevertheless, it is possible to modify the folder’s path and the files you wish to move according to your specific needs. Furthermore, you have the flexibility to rename the folder as per your preference. It is crucial to ensure that you utilize a valid path during this process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import os, shutil lis=[] i=1 # path of the folder "Everything" destination_directory='/Users/Upendra/Desktop/Everything' while os.path.exists(destination_directory): destination_directory+=str(i) i+=1 os.makedirs(destination_directory) #path of the files that you want to move in the folder "Everything" lis=os.listdir('/Users/Upendra/Desktop') for a in lis: print (a) if a==__file__: continue shutil.move(a,destination_directory) |
2. Play random music from a specific folder.
In this example, we are playing a random song from a specific folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import random, os music_directory = 'E:\\Music' #path of the folder from where you want to play music songs = os.listdir(music_directory) song = random.randint(0,len(songs)) # Prints The Song Name print(songs[song]) os.startfile(os.path.join(music_directory, songs[0])) |
3. Play a video from a specific folder.
In this example, we are playing video from a folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import cv2 def play_video(video_path): # Create a VideoCapture object to read the video video_capture = cv2.VideoCapture(video_path) while True: # Read the next frame from the video ret, frame = video_capture.read() if not ret: # End of video break # Display the frameend cv2.imshow('Video', frame) # Wait for a key press and check if it is the 'q' key to exit if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the video capture object and close the video window video_capture.release() cv2.destroyAllWindows() # Example usage video_path = "C:/Users/Upendra/Downloads/video.mp4" play_video(video_path) |
4. Convert a pdf file to an audio (.mp3) file
In this example, we convert the text of the pdf into an audio (.mp3) file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import pyttsx3 import PyPDF2 # path to your PDF file pdf_path = 'D:/projectReportFINAL.pdf' output_audio_path = 'file.mp3' # Open the PDF file with open(pdf_path, 'rb') as file: pdf_reader = PyPDF2.PdfReader(file) total_pages = len(pdf_reader.pages) # Initialize the text-to-speech engine reader = pyttsx3.init() # Iterate through each page of the PDF for page_num in range(total_pages): page = pdf_reader.pages[page_num] text = page.extract_text() # Clean up the extracted text legible_text = text.strip().replace('\n', ' ') print(f"Page {page_num + 1}:") print(legible_text) # Convert the text to an audio reader.save_to_file(legible_text, file.mp3) reader.runAndWait() # Stop the text-to-speech engine reader.stop() print("PDF converted to audio. Audio file saved at:", file.mp3) |
5. Close and Open the tasks
a. Closing a list of tasks that are running.
In this example, we are closing the programs running on the system. The programs that you want to close should be mentioned in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import psutil def close_programs(program_names): for process in psutil.process_iter(): try: process_name = process.name() if any(name.lower() in process_name.lower() for name in program_names): process.kill() print(f"Closed program: {process_name}") except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass # Example usage program_names = ["word.exe"] close_programs(program_names) |
b. Opening a list of tasks
In this example, we opened a program using their location. However, you can change the location as per your requirement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import subprocess def open_program(program_path): try: subprocess.Popen(program_path) print(f"Program opened successfully!") except Exception as e: print(f"Error opening program '{program_path}': {str(e)}") # Example usage program_path = "C:\\Windows\\System32\\notepad.exe" # Open the program open_program(program_path) |
6. Image Compressor
In this example, we are compressing an image (.jpg) file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from PIL import Image def compress_image(input_path, output_path, quality=80): # Open the image file image = Image.open(input_path) # Compress the image image.save(output_path, optimize=True, quality=quality) # Example usage input_path = "E:/Download/QRCode.jpeg" output_path = "/Users/Upendra/image.jpg" compress_image(input_path, output_path) |
7. Convert the color image into a black-and-white image
In this example, we are converting the color image into a black & white image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from PIL import Image # Open the image image_path = "C:/Users/Upendra/Pictures/Perl.jpg" image = Image.open(image_path) # Convert the image to black and white black_white_image = image.convert("L") # Save the black-and-white image output_path = "C:/Users/Upendra/Desktop/image.jpg" black_white_image.save(output_path) print("Image converted to black & white successfully!") |
8. Video to Audio Converter
In this example, we are converting the video (.mp4) file into the audio (.mp3) file.
1 2 3 4 5 6 7 8 9 10 11 12 |
from moviepy.editor import VideoFileClip def video_to_audio_converter(video_path, audio_path): # Load the video file video = VideoFileClip(video_path) # Extract the audio audio = video.audio # Save the audio to a file audio.write_audiofile(audio_path) # Example usage video_path = "C:/Users/Upendra/Downloads/video.mp4" audio_path = "/Users/Upendra/Desktop/output.mp3" video_to_audio_converter(video_path, audio_path) |
9. Convert images(.jpg) to pdf
In this example, we are converting the image (.jpg) file into a pdf.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from fpdf import FPDF def images_to_pdf(image_paths, output_path): pdf = FPDF() # Iterate over each image and add it to the PDF for x in image_paths: pdf.add_page() pdf.image(x, 0, 0, 210, 297) # Adjust width and height as needed # Save the PDF file pdf.output(output_path) # Example usage image_paths = ["C:/Users/Upendra/Pictures/image.jpg"] output_path = "C:/Users/Upendra/Desktop/output.pdf" images_to_pdf(image_paths, output_path) |
10. Automate Database Operation (make a new Excel sheet for the given data)
In this example, we are creating a new Excel sheet for the given data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import os import openpyxl # Automate Excel operations def read_excel(filename, sheet_name): workbook = openpyxl.load_workbook(filename) sheet = workbook[sheet_name] output_data = [] for row in sheet.iter_rows(values_only=True): output_data.append(row) return output_data def write_excel(filename, sheet_name, data): workbook = openpyxl.Workbook() sheet = workbook.active sheet.title = sheet_name for row in data: sheet.append(row) workbook.save(filename) print("Excel file created successfully!") # Example usage data = [ ["Country", "Capital"], ["India", "New Delhi"], ["United States of America", "Washington D.C."], ["United Kingdom", "London"], ["Russia", "Moscow"], ["Japan", "Tokyo"], ["Australia", "Canberra"], ["Germany", "Berlin"], ] output_dir = "C:/Users/Upendra/Desktop" # Change this to the desired directory path filename = os.path.join(output_dir, "Sheet.xlsx") sheet_name = "OutputSheet" write_excel(filename, sheet_name, data) output_data = read_excel(filename, sheet_name) for row in output_data: print(row) |
11. Count the number of tasks running on the system and put it on MS Word
In this example, we are counting the number of processes running on the system and putting the data into MS Word.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import os import psutil from docx import Document # Get the list of running processes running_processes = psutil.process_iter() # Count the number of running tasks and collect their names task_count = 0 task_names = [] for process in running_processes: task_count += 1 task_names.append(process.name()) # Print the number of running tasks print(f"Number of running tasks: {task_count}") # Create a Word document and write the task names document = Document() document.add_heading("Running Tasks", level=1) for i, name in enumerate(task_names): document.add_paragraph(f"Task {i+1}: {name}") # Specify the output path on the desktop desktop = os.path.expanduser("~/Desktop") output_path = os.path.join(desktop, "running_tasks.docx") # Save the Word document on the desktop document.save(output_path) print(f"Word document '{output_path}' created successfully!") |
12. To count the number of video files present on your disk
In this example, we are counting the number of videos present on the disk and listing them in an Excel sheet. In our case, we are searching video files in (E:/) and generating the Excel sheet on the desktop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import os from openpyxl import Workbook # Directory path to search for video files directory = "E:/" # List to store the video file names video_files = [] # Iterate through the directory and its subdirectories for root, dirs, files in os.walk(directory): for file in files: # Check if the file extension is for a video file if file.endswith(('.mp4', '.avi', '.mkv', '.mov', '.wmv')): # Add the file name to the video_files list video_files.append(file) # Create a new Excel workbook and select the active sheet workbook = Workbook() sheet = workbook.active # Write the video file names to the Excel sheet for index, video_file in enumerate(video_files, start=1): sheet.cell(row=index, column=1, value=video_file) # Specify the output file path output_path = "C:/Users/Upendra/Desktop/video_files.xlsx" # Save the Excel workbook workbook.save(output_path) print(f"Video files listed in '{output_path}' successfully!") |
Exploring Advanced Automation Techniques
Advanced automation techniques consist of advanced approaches and technologies used to enhance the capabilities and efficiency of automation scripts. Let us explore some of the advanced automation techniques.
Robotic Process Automation (RPA)
It involves the use of software robots or “bots” to automate repetitive, rule-based tasks that humans mainly perform. RPA bots interact with applications and systems through the user interface and reduce human actions to perform tasks such as data entry, form filling, report generation, etc.
Machine Learning and Artificial Intelligence (AI)
This helps the automation scripts to learn and adapt based on past patterns, data, and feedback. Artificial Intelligence (AI) is widely utilized across various domains, including natural language processing, image recognition, and bolstering the intelligence of automation scripts.
Automated Software Testing
Automated software testing plays a crucial role in evaluating the software’s quality, functionality, and performance. It is one of the most important phases of the Software Development Life Cycle (SDLC). A dynamic shift has been seen over a decade from testing the web and mobile applications manually to automated testing. However, we have a popular cloud-based platform called LambdaTest that provides automated software testing solutions. LambdaTest also supports various frameworks like Selenium, Cypress, etc for automated software testing and has played a key role in cross browser testing.
Cloud Automation
Cloud-based automation provides scalability and flexibility by executing automation scripts and managing resources on cloud platforms. It plays an important role in dynamic scaling and cost optimization since automation scripts can use cloud services and APIs for tasks such as data storage and processing. LambdaTest allows users to execute cloud-based automation testing using Selenium, Cypress, etc that results in faster delivery of high-quality software.
Web Scraping
Web scraping is the process of extracting data and content from other websites, and in this automation scripts play an important role because automation scripts can gather information from multiple web pages and aggregate data for analysis into the other systems.
Web scraping saves time and eliminates manual effort by automating the process of data retrieval from websites, consequently making automation scripts more efficient and powerful.
API Integration
API integration allows automation scripts to interact with external systems, services, or databases, expanding their reach and functionality. Through API integration, automation scripts can exchange data with popular platforms and access real-time information. This technique enables the automation of tasks like retrieving data from a CRM system, posting updates to social media platforms, or fetching data from cloud storage.
Real-World Use Cases of Automation Scripts
Automation scripts are globally adopted across various industries. It helps bring significant benefits in terms of increasing efficiency and accuracy or reducing manual effort.
The followings are a few real-world use cases and success stories of automation script implementations:
Software Testing
Use Case: In Software Development for continuous integration and testing automation.
Challenge: Manual testing during the software development phase is time-consuming, error-prone, and can lead to delays in identifying and fixing defects.
Solution: You can implement automation scripts for continuous integration and testing to ensure early detection of defects and seamless integration of code changes.
Benefits: Automation scripts allow for efficient regression testing and can be triggered automatically upon code changes, providing immediate feedback on the quality and functionality of the software.
Finance and Accounting
Use Case: To automate invoice processing and financial reporting.
Challenge: Manual invoice processing is time-consuming and may have errors.
Solution: Automation scripts can extract data from invoices, validate information, update accounting systems, and generate financial reports automatically.
Benefits: There are various benefits, such as automation reducing manual effort, improving accuracy, accelerating invoice processing times, and many more.
Healthcare
Use Case: In automating patient appointment scheduling and record management.
Challenge: Manual patient appointment scheduling and record management result in inefficiencies, long waiting times, and administrative burdens.
Solution: Automation scripts integrate with scheduling systems, update patient records, send appointment reminders, and generate reports.
Benefits: Automation makes the appointment booking processes smooth, reduces patient wait times, enhances the patient’s experience, and allows healthcare professionals to focus more on patient care.
Manufacturing
Use Case: In automating inventory management and order processing.
Challenge: Manual inventory management and order processing lead to inaccuracies and delays in the supply chain.
Solution: Automation scripts make this easy as it integrates with inventory systems, track stock levels, automate reorder processes, and generate shipping labels.
Benefits: There are several benefits in manufacturing, such as it improves inventory accuracy, optimizing order processing times, reducing stockouts, minimizing manual errors, and also enhances the supply chain.
IT Operations and DevOps
Use Case: In automating software deployment and infrastructure provisioning.
Challenge: Manual software deployment and infrastructure provisioning are time-consuming, error-prone, and affect scalability.
Solution: Automation scripts automate the deployment of software applications, provision virtual machines or containers, and organize complex deployment pipelines.
Benefits: Automation speeds up software releases, improves system stability, enhances scalability, reduces downtime, enables faster incident response, and increases overall operational efficiency.
Marketing
Use Case: In automating social media posting.
Challenge: Manual social media postings are very time-consuming.
Solution: Automation scripts schedule social media posts and can generate performance reports.
Benefits: Automation streamlines social media management, increases posting consistency, and improves targeting audience, enhancing the overall marketing ROI.
These are just a few examples of how automation scripts have been successfully implemented across various industries. From finance and healthcare to manufacturing and marketing, automation scripts have shown their effectiveness in all fields.
Let’s discuss some FAQs related to the automation scripts.
Conclusion
Throughout this extensive guide, we have delved deeply into the significance of automation scripts in optimizing workflows, enhancing productivity, and saving valuable time. Furthermore, we have explored a range of scripting languages, including Python, JavaScript, and more. After that, we discussed some advanced automation techniques, such as automation testing, web scraping, and API integration. And last, we discussed the real-world use cases of automation scripts, followed by some FAQs.
You can also check out our blogs on various categories like Automation, Web Development, Manual Testing, Selenium, Mobile Testing, DevOps, etc.
Frequently Asked Questions (FAQs)
How are the automation scripts different from regular scripts?
Automation scripts are specifically designed to automate repetitive tasks and streamline processes, whereas regular scripts may have a broader range of purposes and functionalities.
What are the specific tools or frameworks available for automation scripting?
There are various tools or frameworks available for automation scripting. For example – Selenium is used for web automation, Appium is used for mobile app automation, and many more.
How can I get started with writing automation scripts?
To get started with automation scripts first you have to familiarize yourself with a scripting language such as Python or JavaScript. Learn the basics of the language, understand automation concepts, and explore relevant libraries or frameworks for your specific use case.
Are there any risks or challenges associated with using automation scripts?
While automation scripts can greatly benefit businesses, some challenges include script maintenance, handling updates or changes in dependencies, ensuring script stability, and addressing potential security vulnerabilities. Regular testing, version control, and adopting best practices can reduce these risks.
Got Questions? Drop them on LambdaTest Community. Visit now