Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering Python Scripting for System Administrators
Mastering Python Scripting for System Administrators

Mastering Python Scripting for System Administrators: Write scripts and automate them for real-world administration tasks using Python

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering Python Scripting for System Administrators

Debugging and Profiling Python Scripts

Debugging and profiling play an important role in Python development. The debugger helps programmers to analyze the complete code. The debugger sets the breakpoints whereas the profilers run our code and give us the details of the execution time. The profilers will identify the bottlenecks in your programs. In this chapter, we'll learn about the pdb Python debugger, cProfile module, and timeit module to time the execution of Python code.

In this chapter, you'll learn about the following:

  • Python debugging techniques
  • Error handling (exception handling)
  • Debugger tools
  • Debugging basic program crashes
  • Profiling and timing programs
  • Making programs run faster

What is debugging?

Debugging is a process that resolves the issues that occur in your code and prevent your software from running properly. In Python, debugging is very easy. The Python debugger sets conditional breakpoints and debugs the source code one line at a time. We'll debug our Python scripts using a pdb module that's present in the Python standard library.

Python debugging techniques

To better debug a Python program, various techniques are available. We're going to look at four techniques for Python debugging:

  • print() statement: This is the simplest way of knowing what's exactly happening so you can check what has been executed.
  • logging: This is like a print statement but with more contextual...

Error handling (exception handling)

In this section, we're going to learn how Python handles exceptions. But first, what is an exception? An exception is an error that occurs during program execution. Whenever any error occurs, Python generates an exception that will be handled using a try…except block. Some exceptions can't be handled by programs so they result in error messages. Now, we are going to see some exception examples.

In your Terminal, start the python3 interactive console and we will see some exception examples:

student@ubuntu:~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 50 / 0


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError...

Debuggers tools

There are many debugging tools supported in Python:

  • winpdb
  • pydev
  • pydb
  • pdb
  • gdb
  • pyDebug

In this section, we are going to learn about pdb Python debugger. pdb module is a part of Python's standard library and is always available to use.

The pdb debugger

The pdb module is used to debug Python programs. Python programs use pdb interactive source code debugger to debug the programs. pdb sets breakpoints and inspects the stack frames, and lists the source code.

Now we will learn about how we can use the pdb debugger. There are three ways to use this debugger:

  • Within an interpreter
  • From a command line
  • Within a Python script

We are going to create a pdb_example.py script and add the following content in that...

Debugging basic program crashes

In this section, we are going to see the trace module. The trace module helps in tracing the program execution. So, whenever your Python program crashes, we can understand where it crashes. We can use trace module by importing it into your script as well as from the command line.

Now, we will create a script named trace_example.py and write the following content in the script:

class Student:
def __init__(self, std):
self.count = std

def go(self):
for i in range(self.count):
print(i)
return
if __name__ == '__main__':
Student(5).go()

The output will be as follows:

student@ubuntu:~$ python3 -m trace --trace trace_example.py
--- modulename: trace_example, funcname: <module>
trace_example.py(1): class...

Profiling and timing programs

Profiling a Python program means measuring an execution time of a program. It measures the time spent in each function. Python's cProfile module is used for profiling a Python program.

The cProfile module

As discussed previously, profiling means measuring the execution time of a program. We are going to use the cProfile Python module for profiling a program.

Now, we will write a cprof_example.py script and write the following code in it:

mul_value = 0
def mul_numbers( num1, num2 ):
mul_value = num1 * num2;
print ("Local Value: ", mul_value)
return mul_value
mul_numbers( 58, 77 )
print ("Global Value: ", mul_value)

Run the program and you will...

Making programs run faster

There are various ways to make your Python programs run faster, such as the following:

  • Profile your code so you can identify the bottlenecks
  • Use built-in functions and libraries so the interpreter doesn't need to execute loops
  • Avoid using globals as Python is very slow in accessing global variables
  • Use existing packages

Summary

In this chapter, we learned about the importance of debugging and profiling programs. We learned what the different techniques available for debugging are. We learned about the pdb Python debugger and how to handle exceptions. We learned about how to use the cProfile and timeit modules of Python while profiling and timing our scripts. We also learned how to make your scripts run faster.

In the next chapter, we are going to learn about unit testing in Python. We are going to learn about creating and using unit tests.

Questions

  1. To debug a program, which module is used?
  2. Check how to use ipython along with all aliases and magic functions.
  3. What is Global interpreted lock (GIL)?
  4. What is the purpose of the PYTHONSTARTUP, PYTHONCASEOK, PYTHONHOME, and PYTHONSTARTUP environment variables?
  1. What is the output of the following code? a) [0], b) [1], c) [1, 0], d) [0, 1].
def foo(k):
k = [1]
q = [0]
foo(q)
print(q)
  1. Which of the following is an invalid variable?
    a) my_string_1
    b) 1st_string
    c) foo
    d) _

Further reading

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • 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

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

Who is this book 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.

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 30, 2019
Length: 318 pages
Edition : 1st
Language : English
ISBN-13 : 9781789134261
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 30, 2019
Length: 318 pages
Edition : 1st
Language : English
ISBN-13 : 9781789134261
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Mastering Python Scripting for System Administrators
€36.99
Mastering Python for Networking and Security
€37.99
Linux Administration Cookbook
€36.99
Total 111.97 Stars icon
Banner background image

Table of Contents

20 Chapters
Python Scripting Overview Chevron down icon Chevron up icon
Debugging and Profiling Python Scripts Chevron down icon Chevron up icon
Unit Testing - Introduction to the Unit Testing Framework Chevron down icon Chevron up icon
Automating Regular Administrative Activities Chevron down icon Chevron up icon
Handling Files, Directories, and Data Chevron down icon Chevron up icon
File Archiving, Encrypting, and Decrypting Chevron down icon Chevron up icon
Text Processing and Regular Expressions Chevron down icon Chevron up icon
Documentation and Reporting Chevron down icon Chevron up icon
Working with Various Files Chevron down icon Chevron up icon
Basic Networking - Socket Programming Chevron down icon Chevron up icon
Handling Emails Using Python Scripting Chevron down icon Chevron up icon
Remote Monitoring of Hosts Over Telnet and SSH Chevron down icon Chevron up icon
Building Graphical User Interfaces Chevron down icon Chevron up icon
Working with Apache and Other Log Files Chevron down icon Chevron up icon
SOAP and REST API Communication Chevron down icon Chevron up icon
Web Scraping - Extracting Useful Data from Websites Chevron down icon Chevron up icon
Statistics Gathering and Reporting Chevron down icon Chevron up icon
MySQL and SQLite Database Administrations Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Chris Hendriks Mar 30, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
lots of typo's, bad examples, no depth
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.