Python and Automation by Nitikesh
Python and Automation by Nitikesh
Introduction
A process which runs automatically without any user guide to full fill the user needs is called
Automation.
Automation can be derived into two types:
1. Industrial Automation
2. IT Automation
Industrial Automation:
Use of electronics tools to minimize the work load for the user to gain more accuracy and
reduce the time scale.
For Industrial Automation, we normally use C/C++ and Python Raspberry pi for Electronic
tools.
For IT Automation, we need to choose the correct Automation Language for the required
Platform.
E.g: Let’s assume you have one Linux OS and you want to use C# for the Automation, then
it will be much more complicated for you to use DOT NET C# in Linux. (You can achieve that
by installing WinBox/Wine in Linux but it is not recommended). So, we have to use Linux
based Languages like Python, Shell scripting, perl, ruby etc.
Recommended Language for Windows/Linux Both is Python. And For Windows it should be
Batch script/C# but for Linux it should be Shell script/Python/any Linux oriented Languages.
Introduction to Python:
Python is a dynamic, interpreted and light weight language. It does not use any variable data types as
this is a scripting language. Extension for python is .py
Note: Scripting languages has no data types. E.g.: php, python etc.
Why Python?
1. Interactive (This makes code short and flexible)
2. Runs in independent platform (in Any OS like Windows/Linux/Mac)
3. Modular (Python uses modules to modularize codes)
4. Open Source (Free of Cost in the market)
5. Extensive libraries
An environment variable is a dynamic-named value that can affect the way running processes will
behave on a computer. They are part of the environment in which a process runs.
If you will set the environment variable for python, then you can use python.exe anywhere from cmd
(Command Prompt) by typing “python <options>”
2. Scroll Down and find Variable name as “Path” and Edit it. Then Add your Python installation
directory there, so that you can access it directly from Command Prompt. In my case I will
add “C:\\python\\” in the Text Box and click on “OK”.
3. Now You can access Python Directly from Cmd. To run a python file command is “Python
<file directory with file name>”. E.g.: python C:\\test\\sum.py
How to install Python 3.x.x in Ubuntu?
As you can compare with the above table, C Language is the faster than the Python and C# code. But
python has the simplest coding format with best Performance. Python checks the variables and its
datatype which takes some time to execute, but you can avoid it and improve performance by using
Cython, numpy, pandas, numba and different Data structure implementations.
What we got?
1. C Program – High Speed – Medium Code Complications – Classic and have very few libraries
2. Python – Medium Speed – Very simple code structure – Advanced and Rich libraries
3. C# - Medium Low Speed – Medium Code Complications – Advanced and Rich libraries
Now even you can choose the best programming Language for any kind of applications using their
compatibility, speed and Complicacy.
For best performance and good Coding structure I am choosing python for describing.
In the next chapter, I will be describing about Python3 basics and will try to complete it in short & wise.
Python3 Input/output:
String is the mixture of characters. It is equivalent to sentence with all special characters.
Here “Hello Dear, how are you.” Is String. And ‘H’,’e’,’l’,’l’,’o’,’,’,’h’,’o’,’w’,’ ‘,’a’,’r’,’e’,’
‘,’y’,’o’,’u’,’.’ are the characters.
# is used for Commenting single line and ‘’’ is used to comment multiline in python.
Python uses Colon (:) to modularize the code statements. After putting Colon (:), you need to give
spaces in the next line to continue with the particular module. (It is called Indentation in python.)
The best practice to use 4 spaces / one tab to modularize the code.
If Statement:
Syntax:
E.g.:
Syntax:
If...elif...else Statement:
Syntax:
E.g.:
Nested If Statement:
Syntax:
Python Looping:
1. While Loop
2. For Loop
While Loop:
Syntax:
While(Condition):
Execution
Statement
E.g.:
For Loop:
Syntax:
Executions/Statements
E.g:
Lists in Python:
E.g:
E.g.:
Dictionaries in Python:
Syntax:
In the above code, using For Loop and Dictionary we have got one better and scalable Python code by
putting username as key and password as value.
String manipulation is a very important factor in Python. Python represents the strings using Single
quote (‘) as well as double quote (“).
String can be access using indexing method. Every string starts with an index of 0.
If we will go from left to right then the indexing starts with 0 and if we will go from right to left
then the indexing starts from -1.
Syntax: stringname[start_index:end_index:steps], default step is 1.
Step represents the difference between the index numbers.
E.g.:str1=”Hello World” , str1[0,4] will give us the output “Hell” , str1[-5:-1] then the o/p is “Worl”
str1[0:6:2] then the o/p is “hlo” because it will take index 0 then index 2 then index 4 then index 6
Using the String slice, we can remove many lines of codes. We can take the example of reverse of a string.
In other languages, we have to write a bunch of codes to get the reverse of a string. But here we can get it
by single line.
It will start from start to end in the steps of -1 which is in reverse order.
Explanation: If we will use Str1[-1:0:-1] then it will give us the out put in reverse order but it will
remove the first character as we have set a limiter as 0. But if we will remove that limiter then we can use
another way to get the reverse of a string as well by using Str1[-1::-1].
You can access the characters from a string using Looping as well.
Tuples in Python:
Tuple is similar to list. But in List, the values are mutable and in Tuple, the values are Immutable.
Mutable means values can be modified in list but in tuple, we can’t change the values
inside it.
Python functions:
Python functions are very important thing for modularize the code and to write a very efficient code base.
E.g.:
In our daily life, we use to work on files and stores them in our systems. For accessing the file, we
normally use MS Word, Notepad and other software’s as they provide more features to accessing and
modifying the data.
Here also we will do the same thing with any other software’s but using python code.
If there is any kind of changes you are doing daily in the file then you can create the python script to make
the work simple and automated. It will save your time and effort seamlessly.
We use “open” function to open the file. Open function takes two arguments. Compulsory one is File’s
Location and optional one is the permission for the file. The default permission is read only. For write, we
use “w”.
If we are opening a file then we need to close the file or it will run in the background process which will
take more memory space each time you will run it.
For more information regarding the Files and its usage, please find the below example.
Python Cheat Sheet:
1. We can use “import” to import other prebuilt or manual modules into our scripts.
E.g.:
2. We can use dir() function to get the sub functions for the given module/class.
3. For reading and writing excel, you must use “xlrd” module.
4. For getting current date and time use datetime module.
After the script has been written, put the .py file it into Folder:
“C:\Users\[Username]\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup\”
It will trigger the program to run in every system start up.
Automation Script for Alerting Bitcoin Price in every Hour.
To get bitcoin price, we will use https://api.coindesk.com/v1/bpi/currentprice/inr.json
For setting it for running in every 1 hour, we will use “Task Scheduler” or a manual python
script as below.
Request module used for handling the GET/POST/.. methods. It sends request to the websites and
will get response from the websites.
Response code 200 means the web site responded to its request.
GET requests a representation of the specified resource. But POST submits data to be processed
to the identified resource. POST is secured than GET.
How to use task scheduler?
Search for task scheduler in search box and open it. Then right click on the Task Scheduler
(Local) and create a new Task
Then Name the Task. In our case I am giving a name “BTC PRICE NOTIFIER”.
Then go to triggers and click on New. Then select daily and repeat in 1 hour for a duration of
indefinitely.
Then go to Actions and Click on new. Then browse the script you want to run. (If want to run
direct python file (.py) then make sure that environment variable is properly set.)
Then click on ok and again click on ok. Now you are done with your scheduler which will run in
every hour to notify you for Bitcoin’s Price.
Extension: .bat