Mastering Python Scripting for System Administrators - Ganesh Sanjiv Naik - E-Book

Mastering Python Scripting for System Administrators E-Book

Ganesh Sanjiv Naik

0,0
40,81 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Leverage the features and libraries of Python to administrate your environment efficiently.




Key Features



  • Learn how to solve problems of system administrators and automate routine activities


  • Learn to handle regular expressions, network administration


  • Building GUI, web-scraping and database administration including data analytics



Book Description



Python has evolved over time and extended its features in relation to every possible IT operation. Python is simple to learn, yet has powerful libraries that can be used to build powerful Python scripts for solving real-world problems and automating administrators' routine activities. The objective of this book is to walk through a series of projects that will teach readers Python scripting with each project.






This book will initially cover Python installation and quickly revise basic to advanced programming fundamentals. The book will then focus on the development process as a whole, from setup to planning to building different tools. It will include IT administrators' routine activities (text processing, regular expressions, file archiving, and encryption), network administration (socket programming, email handling, the remote controlling of devices using telnet/ssh, and protocols such as SNMP/DHCP), building graphical user interface, working with websites (Apache log file processing, SOAP and REST APIs communication, and web scraping), and database administration (MySQL and similar database data administration, data analytics, and reporting).






By the end of this book, you will be able to use the latest features of Python and be able to build powerful tools that will solve challenging, real-world tasks




What you will learn



  • Understand how to install Python and debug Python scripts


  • Understand and write scripts for automating testing and routine administrative activities


  • Understand how to write scripts for text processing, encryption, decryption, and archiving


  • Handle files, such as pdf, excel, csv, and txt files, and generate reports


  • Write scripts for remote network administration, including handling emails


  • Build interactive tools using a graphical user interface


  • Handle Apache log files, SOAP and REST APIs communication


  • Automate database administration and perform statistical analysis



Who this book is for



This book would be ideal for users with some basic understanding of Python programming and who are interested in scaling their programming skills to command line scripting and system administration.






Prior knowledge of Python would be necessary.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 306

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Python Scripting for System Administrators

 

 

 

 

 

 

 

Write scripts and automate them for real-world administration tasks using Python

 

 

 

 

 

 

 

 

 

Ganesh Sanjiv Naik

 

 

 

 

 

BIRMINGHAM - MUMBAI

Mastering Python Scripting for System Administrators

Copyright © 2019 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Vijin BorichaAcquisition Editor: Shrilekha InaniContent Development Editor: Sharon RajTechnical Editor: Prashant ChaudhariCopy Editor:Safis EditingProject Coordinator: Drashti PanchalProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Jyoti Chauhan

First published: January 2019

Production reference: 1240119

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78913-322-6

www.packtpub.com

                                              

I wish to dedicate this book to my Gurudev, His Holiness Dr. Jayant Balaji Athavale. I wish to express gratitude for his guidance on how to become a good human being, a good professional, and a seeker on the path of spiritual progress.

 

                                                                                                                                         

 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the author

Ganesh Sanjiv Naik is an author, consultant, and corporate trainer in the fields of AI, data science, machine learning, the Internet of Things (IoT), and embedded Linux in relation to product development. He has more than 20 years of professional experience in information technology. Ganesh has a passion and a deep desire for teaching. He has trained 2,000+ engineers in Linux and Android product development. He has worked as a corporate trainer for the ISRO, Intel, GE, Samsung, Motorola, Penang Skill Development Center (Malaysia), and various companies in Singapore, Malaysia, and India. He has started a company called Levana Technologies, which works in AI, machine learning, and data science, providing training, projects, and consultancy activities.

I want to thank my wife, Vishalakshi Naik, for providing valuable suggestions, support, and continuous motivation. I also want to thank my colleagues, Mansi Joshi and Kalpesh Patil, who helped me in editing and proofreading, and also provided feedback from a technical perspective. Big thanks to the entire team at Packt, especially Shrilekha Inani, Priyanka Deshpande, and Sharon Raj, for providing me with motivating support throughout the book.

About the reviewers

Yogendra Sharma is a developer with experience in the architecture, design, and development of scalable and distributed applications, with a core interest in microservices and Spring. He is currently working as an IoT and cloud architect at Intelizign Engineering Services Pvt, Pune. He also has hands-on experience in technologies such as AWS Cloud, IoT, Python, J2SE, J2EE, Node.js, Angular, MongoDB, and Docker. He constantly explores technical novelties, and he is open-minded and eager to learn about new technologies and frameworks. He has reviewed several books and video courses published by Packt Publishing.

Abhijeet Mote has a master's degree in computer application (MCA) from University of Mumbai. He is an open source evangelist and works as a senior software engineer. He has worked in multiple domains, including education, media, and IoT. His hobbies involve work on open source projects, and he loves to give back to the open source community by spreading  knowledge of Python and other open source stacks. He conducts training sessions for students, teachers, and enthusiastic developers, and he mentors students for their final year projects. He has been invited to conferences, such as FOSSASIA 2018, and PyGotham, for his contribution in teaching open source technology to enthusiastic developers and underrepresented groups.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Mastering Python Scripting for System Administrators

Dedication

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Python Scripting Overview

Technical requirements

Why Python?

Python syntax compared to other programming languages

Python installation

Installation on the Linux platform

Installation on the Windows platform

Installing and using pip to install packages

Installation on Mac

Installing Jupyter notebook

Installing and using the virtual environment

Installing Geany and PyCharm

Python interpreter

The difference between Python and Bash scripting

Starting the interactive console

Writing scripts with the Python interactive console

Multiple lines

Importing modules through the Python interpreter

Exiting the Python console

The keyboard shortcut

Using the quit() or exit() functions

Indentation and tabs

Variables

Creating and assigning values to variables

Numbers

Number type conversion

Strings

Concatenation (+) and repetition (*)

String slicing

Accessing values in strings

Updating strings

Escape characters

Special string operators

%  string formatting operator

Triple quotes in Python

Strings are immutable

Understanding lists

Accessing values in lists

Updating lists

Deleting list elements

Basic list operations

List operations

Indexing, slicing, and matrices

Tuples

Accessing values in tuples

Updating tuples

Deleting tuple elements

Basic tuple operations

Indexing, slicing, and matrices

max() and min()

Sets

Dictionaries

Parsing command-line arguments

Command-line arguments in Python

Sys.argv

Decision making

Python if statement syntax

Python if...else statement syntax

Python if...elif...else statement

Loops

for loop

The range() function

while loop

Iterators

Generators

How to create a generator in Python?

Functions

The return statement

Lambda functions

Modules

Importing modules

Summary

Questions

Further reading

Debugging and Profiling Python Scripts

What is debugging?

Python debugging techniques

Error handling (exception handling)

Debuggers tools

The pdb debugger

Within an interpreter

From a command line

Within a Python script

Debugging basic program crashes

Profiling and timing programs

The cProfile module

timeit

Making programs run faster

Summary

Questions

Further reading

Unit Testing - Introduction to the Unit Testing Framework

What is unittest?

Creating unit tests

Methods used in unit testing

Summary

Questions

Further reading

Automating Regular Administrative Activities

Accepting input by redirection, pipe, and input files

Input by redirection

Input by pipe

Input by input file

Handling passwords at runtime in scripts

Executing external commands and getting their output

Capturing output using the subprocess module

Prompting for passwords during runtime and validation

Reading configuration files

Adding logging and warning code to scripts

Generating warnings

Putting limits on CPU and memory usage

Launching webbrowser

Using the os module for handling directory and files

Creating and deleting the directory

Examining the content of a filesystem

Making backups (with rsync)

Summary

Questions

Further reading

Handling Files, Directories, and Data

Using the os module to work with directories

Get the working directory

Changing the directory

Listing files and directories

Renaming a directory

Copying, moving, renaming, and deleting data

Copying the data

Moving the data

Renaming data

Deleting data

Working with paths

Comparing data

Merging data

Pattern matching files and directories

Metadata: data about data

Compressing and restoring

Using the tarfile module to create TAR archives

Using a tarfile module to examine the contents of TAR files

Summary

Questions

Further reading

File Archiving, Encrypting, and Decrypting

Creating and unpacking archives

Creating archives

Unpacking archives

Tar archives

ZIP creation

File encryption and decryption

Summary

Questions

Further reading

Text Processing and Regular Expressions

Text wrapping

The wrap() function

The fill() function

The dedent() function

The indent() function

The shorten() function

Regular expressions

The match() function

The search() function

The findall() function

The sub() function

Unicode strings

Unicode code point

Encoding

Decoding

Avoiding UnicodeDecodeError

Summary

Questions

Further reading

Documentation and Reporting

Standard input and output

Information formatting

Sending email

Summary

Questions

Further reading

Working with Various Files

Working with PDF files

Reading a PDF document and getting the number of pages

Extracting text

Rotating PDF pages

Working with Excel files

Using the xlrd module

Reading an Excel file

Extracting the names of columns

Using pandas 

Reading an Excel file

Reading specific columns in an Excel file

Using openpyxl

Creating a new Excel file

Appending values

Reading multiple cells

Working with CSV files

Reading a CSV file

Writing into a CSV file

Working with txt files

The open() function

File opening

The close() function

Writing a text file

Reading a text file

Summary

Questions

Further reading

Basic Networking - Socket Programming

Sockets

The http package

The http.client module

The http.server module

The ftplib module

Downloading files

Getting a welcome message using getwelcome():

Sending commands to the server using the sendcmd() function

The urllib package

Python urllib response headers

Summary

Questions

Further reading

Handling Emails Using Python Scripting

Email message format

Adding HTML and multimedia content

POP3 and IMAP servers

Receiving email using the poplib library

Receiving email using the imaplib library

Summary

Questions

Remote Monitoring of Hosts Over Telnet and SSH

The telnetlib() module

SSH

The subprocess.Popen() module

SSH using fabric module

SSH using the Paramiko library

SSH using the Netmiko library

Summary

Questions

Further reading

Building Graphical User Interfaces

Introduction to GUI

Using a library to create a GUI-based application

Installing and using the Apache Log Viewer app

Summary

Questions

Further reading

Working with Apache and Other Log Files

Parsing complex log files

The need for exceptions

Analyzing exceptions

Tricks for parsing different files

Error log

Access log

Common log format

Parsing other log files

Summary

Questions

Further reading

SOAP and REST API Communication

What is SOAP?

Using libraries for SOAP

What is a RESTful API?

Using standard libraries for RESTful APIs

Working with JSON data

Summary

Questions

Further reading

Web Scraping - Extracting Useful Data from Websites

What is web scraping?

Data extraction

The requests library

The beautifulsoup library

Extracting information from Wikipedia

Summary

Questions

Further reading

Statistics Gathering and Reporting

NumPY module

Using arrays and scalars

Array indexing

Indexing a 2D array

Universal array functions

Pandas module

Series

DataFrames

Data visualization

Matplotlib

Histograms

Scatter plots

Bar charts

Plotly

Scatter plots

Line scatter plots

Box plots

Contour plots

Summary

Questions

Further reading

MySQL and SQLite Database Administrations

MySQL database administration

Getting a database version

Creating a table and inserting data

Retrieving the data

Updating the data

Deleting the data

SQLite database administration

Connecting to the database

Creating a table

Inserting the data

Retrieving the data

Updating the data

Deleting the data

Summary

Questions

Further reading

Assessments

Chapter 1, Python Scripting Overview

Chapter 2, Debugging and Profiling Python Scripts

Chapter 3, Unit Testing – Introduction to the Unit Testing Framework

Chapter 4, Automating Regular Administrative Activities

Chapter 5, Handling Files, Directories, and Data

Chapter 6, File Archiving, Encrypting, and Decrypting

Chapter 7, Text Processing and Regular Expressions

Chapter 8, Documentation and Reporting

Chapter 9, Working with Various Files

Chapter 10, Basic Networking – Socket Programming

Chapter 11, Handling Emails Using Python Scripting

Chapter 12, Remote Monitoring of Hosts Over Telnet and SSH

Chapter 13, Building Graphical User Interfaces

Chapter 14, Working with Apache and Other Log Files

Chapter 15, SOAP and REST API Communication

Chapter 16, Web Scraping – Extracting Useful Data from Websites

Chapter 17, Statistics Gathering and Reporting

Chapter 18, MySQL and SQLite Database Administrations

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Python has evolved and extended its features toward every possible IT operation. This book will help you leverage the latest features of Python to write effective scripts and create command-line tools (for use when it comes to data types, loops, conditionals, functions, error handling, and more) to administer your environment. This book will revolve around the entire development process, from setup and planning to automated testing and building different command-line tools. This book gets you up and running with everything from basic scripting to using standard library packages. Finally, you will create a large scripting project where you will learn how to plan, implement, and distribute a project based on ideal resources.

Who this book is for

This book would be ideal for users with some basic understanding of Python programming who are interested in scaling their programming skills to command-line scripting and system administration.

Prior knowledge of Python is necessary.

What this book covers

Chapter 1, Python Scripting Overview, covers the installation procedures for Python as well as the use of the Python interpreter tool. You will learn how to assign values to variables and be introduced to variables and strings. You will study the sequence data types, including lists, tuples, sets, and dictionaries. Also, you will learn how to parse command-line options in scripts. 

Chapter 2, Debugging and Profiling Python Scripts, teaches you how to debug Python programs using debugger tools. You will also learn how to handle errors, and explore the concepts of profiling and timing.

Chapter 3, Unit Testing – Introduction to the Unit Testing Framework, is about unit testing in Python. We will create unit tests to test programs.

Chapter 4, Automating Regular Administrative Activities, will teach you how to automate the regular administrative activities of the system administrator. You will learn about accepting inputs, handling passwords, the execution of external commands, reading config files, adding warning codes to scripts, implementing CPU limits, web browser launching, use of the os module, and taking backups.

Chapter 5, Handling Files, Directories, and Data, is where you will learn about using the os module for various activities. You will learn about the data and some methods applied to that data, such as copying, moving, merging, and comparing. You will also learn about the tarfile module and how to use it.

Chapter 6, File Archiving, Encrypting, and Decrypting, delves into file archiving, creating archives, and TAR and ZIP creation. You will also learn about unpacking the .tar and .zip files using applications.

Chapter 7, Text Processing and Regular Expressions, looks at text processing and regular expressions in Python. Python has a very powerful library of things called called regular expressions, which do tasks such as searching and extracting data. You will learn how to use regular expressions with files. You will also learn how to read and write to files.

Chapter 8, Documentation and Reporting, will teach you how to document and report information using Python. You will also learn how to take input using Python scripts and how to print the output. Using Python, you can write scripts for automated information gathering. Writing scripts for receiving emails is easier in Python. You will learn how to format information.

Chapter 9, Working with Various Files, will go into the issue of handling various files, such as PDF files, Excel files, and CSV files. You will learn how to open, edit, and get data from these files using Python.

Chapter 10, Basic Networking – Socket Programming, will first introduce the basics of networking; then you will learn about sockets such as TCP, UDP, and more. You will also learn about how to program sockets to communicate and get information of protocols such as HTTP and FTP.

Chapter 11, Handling Emails Using Python Scripting, explores how to compose and send emails using Python scripts. Sending emails is a very common task in any software program. We can use Python's smtplib module for sending emails in Python programs. In this chapter, you will also learn about the different protocols used for sending emails on different servers.

Chapter 12, Remote Monitoring of Hosts Over Telnet and SSH, shows you how to carry out basic configurations on a server with the SSH protocol. We will begin by using the Telnet module, after which we will implement the same configurations using the preferred method, SSH.

Chapter 13, Building Graphical User Interface, looks at graphical user interface creation with the PyQt module.

Chapter 14, Working with Apache and Other Log Files, explains how to work with Apache log files. You will also learn about log-parsing applications; that is, identifying the particular types of log messages. You will also learn how to parse these files and how to handle multiple files; detecting any exceptions, storing data, and producing reports.

Chapter 15, SOAP and REST API Communication, concerns the basics of SOAP and REST, and the differences between them. You will also get to know the SOAP API and how to use it using different libraries. We will also study the REST API and standard libraries.

Chapter 16, Web Scraping – Extracting Useful Data from Websites, will teach you about extracting data from a website using Python’s libraries. You will also learn how to search for articles and source code using Python.

Chapter 17, Statistics Gathering and Reporting, is about advanced Python libraries that are used in scientific calculations. These libraries are NumPy, SciPy, and Matplotlib. You will learn about the concepts of data visualization and learn how to plot data.

Chapter 18, MySQL and SQLite Database Administrations, looks at database administration using MySQL and SQLite databases. You will learn about the requirements and design for this kind of administration, how to modify the plugin framework, and how to write producer and consumer code.

To get the most out of this book

We wrote this book to be as accessible as possible and to teach you many different approaches to programming with Python through several scripts. However, to get the most out of them, you need to do the following:

Have a Linux system set up and configured for testing/debugging scripts

Understand the created scripts

Keep in mind what the components of each script are

Check how the components could be reused or combined in new ways

This book assumes a certain level of Python knowledge to begin your journey; these basic skills will not be covered in this book. These skills include the following:

How to set up and configure a Linux system

How to install, access, and configure a specific Python IDE (although several are already included in most Linux distributions)

Some basics about computing and programming (although we will do our best to provide a crash course)

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub  https://github.com/PacktPublishing/Mastering-Python-Scripting-for-System-Administrators-/. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: " To unpack the archives shutilmodule hasunpack_archive()function."

A block of code is set as follows:

>>> 3 * 'hi' + 'hello''hihihihello'

Any command-line input or output is written as follows:

sudo apt install python3-pip

Bold: Indicates a new term, an important word, or words that you see onscreen. Here is an example: " TheCSVformat, which stands forComma Separated Valuesformat."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com

Python Scripting Overview

Python is a scripting language, created by Guido van Rossum in 1991, which is used in various applications, such as game development, GIS programming, software development, web development, data analytics, machine learning, and system scripting.

Python is an object-oriented, high-level programming language with dynamic semantics. Mainly, Python is an interpreted language. Python is used for rapid application development, as it has all of the advanced features for development.

Python is simple and easy to learn, as its syntax makes programs more readable. Hence, the program maintenance cost is low.

Python has one more important feature of importing modules and packages. This feature allows for code reuse. The Python interpreter is easy to understand. We can write the complete code one by one in it and, as Python is an interpreted language, the code gets executed line by line. Python also has a wide range of libraries for advanced functionality.

This chapter will cover the following topics:

Python scripting

Installing and using Python and various tools

Variables, numbers, and strings

Python supported data structures and how to use all of these concepts in a script

Decision making; that is, the 

if

statement

Looping statements; that is, the 

for

and

while

loops

Functions

Modules

Technical requirements

Before you start reading this book, you should know the basics of Python programming, such as the basic syntax, variable types, tuple data type, list dictionary, functions, strings, and methods. Two versions, 3.7.2 and 2.7.15, are available at python.org/downloads/. In this book we'll work with version 3.7 for code examples and package installing.

Examples and source code for this chapter are available in the GitHub repository: https://github.com/PacktPublishing/Mastering-Python-Scripting-for-System-Administrators-.

Why Python?

Python has a wide range of libraries for open source data analysis tools, web frameworks, testing, and so on. Python is a programming language that can be used on different platforms (Windows, Mac, Linux, and embedded Linux H/W platforms, such as Raspberry Pi). It's used to develop desktop as well as web applications.

Developers can write programs with fewer lines if they use Python. Prototyping is very quick, as Python runs on an interpreter system. Python can be treated in an object-oriented, a procedural, or a functional way.

Python can do various tasks, such as creating web applications. It is used with the software to create workflows; it connects to database systems, handles files, handles big data, and performs complex mathematics.

Python syntax compared to other programming languages

The code written in Python is highly readable because it's similar to the English language. To complete a command, Python uses new lines.

Python has a great feature: indentation. Using indentations, we can define the scope for decision-making statements, loops such as for and while loops, functions, and classes.

Python installation

In this section, we will be learning about the installation of Python on different platforms, such as Linux and Windows.

Installation on the Linux platform

Most Linux distributions have Python 2 in their default installations. Some of them also have Python 3 included.

To install python3 on Debian-based Linux, run the following command in the Terminal:

sudo apt install python3

To install python3 on centos, run the following command in the Terminal:

sudo yum install python3

If you are unable to install Python using the preceding commands, download Python from https://www.python.org/downloads/ and follow the instructions.

Installation on the Windows platform

For installing Python in Microsoft Windows, you'll have to download the executable from python.org and install it. Download python.exe from https://www.python.org/downloads/ and choose the Python version that you want install on your PC. Then, double-click on the downloaded exe and install Python. On the installation wizard, there's checkbox that says Add Python to the path. Check this checkbox and then follow the instructions to install python3.

Installing and using pip to install packages

In Linux, install pip as follows:

sudo apt install python-pip --- This will install pip for python 2.

sudo apt install python3-pip --- This will install pip for python 3.

In Windows, install pip as follows:

python -m pip install pip

Installation on Mac

To install python3, first we must have brew installed on our system. To install brew on your system, run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

By running the preceding command. brew will get installed. Now we will install python3 using brew:

brew install python3

Installing Jupyter notebook

For installing the Jupyter Notebook, download Anaconda.

Install the downloaded version of Anaconda and follow the instructions on the wizard.

Install Jupyter using pip:

pip install jupyter

In Linux, pip install jupyter will install Jupyter for python 2. If you want to install jupyter for python 3, run the following command:

pip3 install jupyter

Installing and using the virtual environment

Now we will see how to install the virtual environment and how to activate it. 

To install the virtual environment on Linux, perform the following steps:

First check whether

pip

is installed or not. We are going to install

pip

for

python3

sudo apt install python3-pip

Install the virtual environment using

pip3

:

sudo pip3 install virtualenv

Now we will create the virtual environment. You can give it any name; I have called it

pythonenv

:

virtualenv pythonenv

Activate your virtual environment:

source venv/bin/activate

After your work is done, you can deactivate

virtualenv

 by using following command:

deactivate

In Windows, run the pip install virtualenv command to install the virtual environment. The steps for installing virtualenv are same as with Linux.

Installing Geany and PyCharm

Download Geany from https://www.geany.org/download/releases and download the required binaries. Follow the instructions while installing.

Download PyCharm from https://www.jetbrains.com/pycharm/download/#section=windows and follow the instructions.

Python interpreter

Python is an interpreted language. It has an interactive console called the Python interpreter or Python shell. This shell provides a way to execute your program line by line without creating a script.

You can access all of Python's built-in functions and libraries, installed modules, and command history in the Python interactive console. This console gives you the opportunity to to explore Python. You're able to paste code into scripts when you are ready.

The difference between Python and Bash scripting

In this section, we're going to learn about the difference between Python and Bash scripting. The differences are as follows:

Python is a scripting language, whereas Bash is a shell used for entering and executing commands

Dealing with larger programs is easier with Python

In Python, you can do most things just by calling a one-line function from imported modules

Starting the interactive console

We can access Python's interactive console from any computer that has Python already installed. Run the following command to start Python's interactive console:

$ python

This will start the default Python interactive console.

In Linux, if we write Python in the Terminal, the python2.7 console starts. If you want to start the python3 console, then enter python3 in the Terminal and press Enter.

In Windows, when you enter Python in Command Prompt, it will start the console of the downloaded Python version.

Importing modules through the Python interpreter

If you are importing any module, then the Python interpreter checks if that module is available or not. You can do this by using the import statement. If that module is available, then you will see the >>> prefix after pressing the Enter key. This indicates that the execution was successful. If that module doesn't exist, the Python interpreter will show an error:

>>> import time

>>>

After importing the time module, we get the >>> prefix. This means that the module exists and this command gets executed successfully:

>>> import matplotlib

If the module doesn't exist, then you will get Traceback error:

File "<stdin>", line 1, in <module>

ImportError: No module named 'matplotlib'

So here, matplotlib isn't available, so it gives an error: ImportError: No module named 'matplotlib'.

To solve this error, we will have to install matplotlib and then again try to import matplotlib. After installing matplotlib, you should be able to import the module, as follows:

>>> import matplotlib

>>>

Exiting the Python console

We can come out of the Python console in two ways:

The keyboard shortcut: 

Ctrl + D

Using the 

quit()

or

exit()

functions

The keyboard shortcut

The keyboard shortcut, Ctrl + D, will give you the following code: