Is python good for automating tasks?
Show
Tired of performing repetitive tasks every day? Well, it can bore even the most resilient of us out of our minds. Lucky for us, the digital age we live in offers us a bevy of tools to relieve ourselves of that sort of tedious labor. One of them is Python - a perfect programming language to start your journey with task automation. In this article, we will share the reasons to automate tasks with Python and present six ideas with real-life examples. The first four Python automation examples are by me, and the two last, by Arzu Huseynov. While these task automation examples are simple, they can work as a foundation if you would like to build automating Python scripts to fully perform IT automation with Python. Table of content:
How to Start With Task Automation?First of all, I’m here to tell you that automation is definitely for you, even if you’re a complete newbie to the field. Even though it might seem daunting at first, I promise you that building your first script will feel very rewarding and your new skills will save you lots of time in the long run. Here's a brief step-by-step guide to begin with:
Once you find a suitable task, you have to choose the right tool. It shouldn't come out as a surprise that the "tool" I'm going to explore is Python (speaking from a Python developer's perspective). Among the sheer diversity of languages available, Python is relatively easy to learn and has proven itself useful in a variety of fields. Why Use Python For Task Automation?Python offers great readability and approachable syntax. The latter resembles plain English, which makes it an excellent choice to start your journey with. When compared with other languages, Python clearly stands out as one of the simplest in the bunch. Look at this example of code written in C++ and Python. Sample code in C++ In Python, the same functionality took fewer lines written in simpler, friendlier syntax. The advantages of Python I mentioned above make the learning process fast and pleasant. With little time and effort, you will gain enough knowledge to write simple scripts. This smooth learning curve significantly speeds up development, even for experienced developers. The learning curve for Python vs other programming languages Another thing that may convince you to use Python is that it comes with great data structure support. Data structures enable you to store and access data, and Python offers many types thereof by default, including lists, dictionaries, tuples, and sets. These structures let you manage data easily, efficiently, and, when chosen correctly, increase software performance. Furthermore, the data is stored securely and in a consistent manner. Even better, Python lets you create your own data structures, which, in turn, makes the language very flexible. While data structures may not seem all that important to a newcomer, trust me on this — the deeper you go, the more important your choice of data structure tends to become. You can automate nearly everything with Python. From sending emails and filling out PDFs and CSVs (if you are not familiar with this file format I advise you to check it, it’s for example used by Excel) to interacting with external APIs and sending HTTP requests. Whatever your idea is, it’s more than likely that you can pull it off using Python along with its modules and tools. Tons of libraries created for Python make the language really powerful, allowing developers to tackle everything from machine learning and web scraping to managing your computer’s operating system. Where Python finds its use Python’s strengths also include a decent support structure and a large community of enthusiasts. The language continues to grow in popularity and articles covering basically all of the concepts underpinning the language keep popping up on the Web — a cursory search is bound to yield some pretty interesting blog or StackOverflow posts, and if it doesn’t, you can always post a question or problem you have to any one of the Python forums around the Web. Trust me, you won’t stay alone with your problem for long. Python has a great community around it and the language itself is in constant development. Plus, there are new third-party libraries showing up all the time. Far from a darling of the software development community, Python has found use across a number of professions and industries, including science, data analysis, mathematics, networking, and more. What Can You Automate With Python?Almost everything! With a little bit of work, basically, any repetitive task can be automated. To do that, you only need Python on your computer (all of the examples here were written in Python 3) and the libraries for a given problem. I’m not going to teach you Python, just show that automation is easy with it. In the examples below, I used iPython, which is a tool that helps to write the code interactively, step by step. For simple automation, Python’s built-in libraries should be enough. In other cases, I will let you know what should be installed. Reading and writing filesReading and writing files is a task that you can efficiently automate using Python. To start, you only need to know the location of the files in your filesystem, their names, and which mode you should use to open them. In the example below, I used the with statement to open a file — an approach I highly recommend. Once the with block code is finished, the file is closed automatically and the cleanup is done for us. You can read more about it in the official documentation. Let’s load the file using the open() method. Open() takes a file path as the first argument and opening mode as the second. The file is loaded in read-only mode (‘r’) by default. To read the entire content of a file, use the read() method.
To read the content line by line, try the readlines() method — it saves the contents to a list.
You can also modify the contents of a file. One of the options for doing so is loading it in write (‘w’) mode. The mode is selected via the second argument of the open() method. But be careful with that, as it overwrites the original content!
One great solution is to open the file in append (‘a’) mode, which means that new content will be appended to the end of the file, leaving the original content untouched.
As you can see, reading and writing files is super easy with Python. Feel free to read more about the topic, especially the modes of opening files because they can be mixed and extended! Combining writing to a file with Web scraping or interacting with APIs provides you with lots of automating possibilities! As a next step, you could also check a great library, csv, which helps with reading and writing CSV files. Sending emailsAnother task that can be automated with Python is sending emails. Python comes bundled with the great smtplib library, which you can use to send emails via the Simple Mail Transfer Protocol (SMTP). Read on to see how simple it is to send an email using the library and Gmail’s SMTP server. You will need an email account in Gmail, naturally, and I strongly recommend you create a separate account for the purpose of this script. Why? Because you’ll need to set the Allow less secure apps option to ON, and this makes it easier for others to gain access to your private data. Set up the account now and let’s jump into code once you’re done. First of all, we will need to establish an SMTP connection.
The requisite, built-in modules are imported at the beginning of the file, we use getpass to securely prompt for the password and smtplib to establish a connection and send emails. In the following steps, the variables are set. HOST and PORT are both required by Gmail — they’re the constants, which is why they’re written in uppercase. Next, you provide your Gmail account name that will be stored in the username variable and type in the password. It’s good practice to input the password using the getpass module. It prompts the user for a password and does not echo it back after you type it in. Then, the script starts a secure SMTP connection, using the SMTP_SSL() method. The SMTP object is stored in the server variable.
Finally, you authenticate yourself using the login() method and… that’s it! From now on, you will be able to send emails with the sendmail() method. Please remember to clean up afterward, using the quit() method. Web scrapingWeb scraping allows you to extract data from Web pages and save it on your hard drive. Imagine your workday involves pulling data from a website you visit every day. Scraping could be of much help in such a case, as once code is written it can be run many times, making it especially useful when handling large amounts of data. Extracting information manually takes a lot of time and a lot of clicking and searching. With Python, it couldn’t be easier to scrape data from the Web. But in order to analyze and extract data from HTML code, the target page has to be downloaded first. The requests library will do the job for us, but you need to install it first. Simply type the following in your console:
(for more details, check the official documentation: https://requests.readthedocs.io/en/master/user/install/#install) With the page downloaded, we can now extract the actual data we want. This is where BeautifulSoup comes in. The library helps with parsing and pulling data from structured files. Naturally, the library also has to be installed first. Like before, type the following in your console:
(for more details, check the official documentation) Let’s run through a rather simple example to see how the automation bit works here. The HTML code of a webpage we selected for parsing is really brief, and small given that its purpose is to show what week of the year it is. See it here: What Week Is It. To inspect the HTML code, simply right-click anywhere on the page and choose View page source. Then run the interactive Python (by simply typing ipython in the console) and let’s start fetching the page using requests:
With that done, the page is then downloaded and stored in a response variable. If you want to see its contents, type response.content in the interactive terminal. The HTTP status code 200 tells us that the request succeeded. Now it’s time for BeautifulSoup to do its job. We start with importing the library and then creating a BeautifulSoup object called soup. The soup object is created with the fetched data as an input. We also let the library know which parser should be utilized, with html.parser for HTML pages, obviously.
The HTML document is now saved in the soup object. It’s represented as a nested structure (its fragment is printed above). There are several ways to navigate through the structure. A few of them are shown below.
You can easily extract the title of the page or find all the tags in the data. The best way to get a feeling for it is to fiddle with the object yourself. Let’s try to extract the information we wanted at the very beginning. What week of the year is it? Studying the HTML code, we will see that the information is hidden in a table, under the
Bài Viết Liên QuanQuảng CáoCó thể bạn quan tâmToplist được quan tâm#2
#3
#4
Top 6 thử thách thần chết thuyết minh phần 2 20235 tháng trước#5
#6
Top 5 áo khoác nam quảng châu cao cấp 20235 tháng trước#7
#8
Top 9 mẫu đồng phục công sở đẹp 2022 20235 tháng trước#9
Top 5 ốp lưng iphone 13 pro bảo vệ camera 20235 tháng trướcQuảng cáoXem NhiềuQuảng cáoChúng tôiTrợ giúpBản quyền © 2021 boxhoidap.com Inc.
|