Pro python system administration second edition free download






















You can use comments to explain one or more lines of code. These should be used in moderation and where appropriate. You can also use docstrings to document your modules, functions, methods, and classes.

This will help you develop good Python coding practices. There are several other style guides for Python. Sometimes looking at different style guides will help you develop good practices as well. Finally, you learned about several tools you can use to help you make your code better. If you have the time, I encourage you to check out PyFlakes or Flake8 especially as they can be quite helpful in pointing out common coding issues in your code. Review Questions 1. How do you create a comment? What do you use a docstring for?

Why is documenting your code important? Chapter 4 - Working with Strings You will be using strings very often when you program. A string is a series of letters surrounded by single, double or triple quotes. You can cast other types to a string using the built-in str function. Also, note that using triple quotes allows you to create multi-line strings.

Any whitespace within the string will also be included. String Methods In Python, everything is an object. You will learn how useful this can be in chapter 18 when you learn about introspection. For now, just know that strings have methods or functions that you can call on them.

For example,. You can ignore these for now as they are used more for intermediate and advanced use-cases. You will find that the. You can use. This is especially useful when you are reading in a text file that you need to parse. In fact, you will often end up stripping end-of-line characters from strings and then using. Now normally you would assign this result to a variable, but for demonstration purposes, you can skip that part. When doing string parsing for work, I personally have found that you can use the.

Occasionally you will find that you might also need to use Regular Expressions regex , but most of the time these two methods are enough. String Formatting String formatting or string substitution is where you have a string that you would like to insert into another string. This is especially useful when you need to create a template, such as a form letter. But you will use string substitution a lot for debugging output, printing to standard out and much more. Standard out or stdout is a term used for printing to the terminal.

But it is good to understand how all three work. Note: This type of formatting can be quirky to work with and has been known to lead to common errors such as failing to display Python tuples and dictionaries correctly. Using either of the other two methods is preferred in that case. You can also do string formatting with multiple variables.

In fact, there are two ways to do this. You must be at least 18 to continue! To pass in multiple items, you use the percent sign followed by a tuple of the items to insert.

Formatting Strings Using. While this book will focus on using f-strings, you will find that. This example uses positional arguments. Instead of passing a dictionary to. You can also repeat a variable multiple times in the string when using. Why do they call you Mike? You must be at least Mike to continue! A common coding style when working with. The colon : tells Python that you are going to apply some kind of formatting.

In the first example, you are specifying that the string be left aligned and 20 characters wide. The second example is also 20 characters wide, but it is right aligned. At this point, you should be pretty familiar with the way. These expressions tell the fstring about any special processing that needs to be done to the inserted string, such as justification, float precision, etc.

The f-string was added in Python 3. However, your curly braces must enclose something. Because of the fact that f-strings are evaluated at runtime, you can put any valid Python expression inside of them.

They will simplify your code quite a bit if you use them wisely. You should definitely give them a try. String Concatenation Strings also allow concatenation, which is a fancy word for joining two strings into one.

String Slicing Slicing in strings works in much the same way that it does for Python lists. If you want to, you can drop the zero as that is the default and use [:4] instead, which is what example two does. You can also use negative position values. So [] means that you want to start at the end of the string and get the last four letters of the string. You will learn more about slicing in chapter 6, which is about the list data type.

You should play around with slicing on your own and see what other slices you can come up with. Wrapping Up Python strings are powerful and useful. They can be created using single, double, or triple quotes.

Strings are objects, so they have methods. You also learned about string concatenation, string slicing, and three different methods of string formatting.

The newest flavor of string formatting is the f-string. It is also the most powerful and the currently preferred method for formatting strings. What are 3 ways to create a string? Run dir "". This lists all the string methods you can use. Which of these methods will capitalize each of the words in a sentence? You are 21 years old. How do you concatenate these two strings together? The built-in numeric types are: int float complex Python 2 also had the long numeric type, which was an integer able to represent values larger than an int could.

In Python 3, int and long were combined so that Python 3 only has int. You can create an int by simply typing the number or by using int. In Python, you can create a float by typing it or by using float. A complex number has a real and an imaginary part.

The real and imaginary parts are accessed using attribute notation:. Complex numbers can be created by either typing them or using complex. There are two other numeric types that are included with Python in its standard library. Integers You can create an integer in two ways in Python. In fact, int is usually used for converting a string or other type to an integer. Another term for this is casting.

A little known feature about int is that it takes an optional second argument for the base in which the first argument is to be interpreted. In other words, you can tell Python to convert to base2, base8, base16, etc. Floats A float in Python refers to a number that has a decimal point in it. For example, 2. You can also cast string or floats to int using the int built-in from the previous section.

Note: The float numeric type is inexact and may differ across platforms. Complex Numbers A complex number has a real and an imaginary part, which are each a floating-point number.

Then you extract the real and imag parts from the complex number. Numeric Operations All the numeric types, with the exception of complex, support a set of numeric operations. Here you learned a little about how Python handles int, float, and complex number types.

You can use these types for working with most operations that involve numbers. It is tailor-made for working with that type of number. What 3 numeric types does Python support without importing anything? Which module should you use for money or other precise calculations? Give an example of how to use augmented assignment. Chapter 6 - Learning About Lists Lists are a fundamental data type in the Python programming language. A list is a mutable sequence that is typically a collection of homogeneous items.

Mutable means that you can change a list after its creation. You will frequently see lists that contain other lists. These are known as nested lists. You will also see lists that contain all manner of other data types, such as dictionaries, tuples, and other objects. Creating Lists There are several ways to create a list.

You may construct a list in any of the following ways: Using a pair of square brackets with nothing inside creates an empty list: [] Using square brackets with comma-separated items: [1, 2, 3] Using a list comprehension see Chapter 13 for more information : [x for x in iterable] Using the list function: list iterable An iterable is a collection of items that can return its members one at a time; some iterables have an order i.

Lists themselves are sequences. Strings are sequences as well. You can think of strings as a sequence of characters. Here you create a list with 3 numbers in it. Then you print it out to verify that it contains what you think it should. It automatically iterates over the characters in the string to create a list of three strings, where each string is a single character.

The second easiest way is to call list without any arguments. You will be learning more about methods throughout this book and by the end you will understand them quite well! A Python list has several methods that you can call. A method allows you to do something to the list.

Here is a listing of the methods you can use with a list: append clear copy count extend index insert pop remove reverse sort Most of these will be covered in the following sections.

You can use count to count the number of instances of the object that you passed in. That is what inplace means. Adding to a List There are three list methods that you can use to add to a list. Then you append an integer to the end of the list. Now the list should have 5 items in it with the 1 on the end. But what if you wanted to add an element somewhere other than the end of the list? There are two other ways to add items to a list. The extend method will iterate over the items in the passed in list and add each of them to the list.

Accessing and Changing List Elements Lists are made to be worked with. You will need to learn how to access individual elements as well as how to change them.

In the example above, you access the first and third elements. Try using some other values and see if you can get the first item using negative indexing. Deleting From a List Deleting items from a list is pretty straight-forward. There are 4 primary methods of removing items from a list: clear pop remove del You can use clear to remove everything from the list.

This can be useful when you have finished working on the items in the list and you need to start over from scratch. If it is important for you to always use the same object, then using clear would be better. If that does not matter, then setting it to an empty list will work well too.

If you would rather remove individual items, then you should check out pop or remove. Or you can call pop without an argument, like in the example above, and it will default to removing the last item in the list and returning it. So in this case, you tell the list to remove the first occurrence of the number 8.

ValueError: list. Sorting a List Lists in Python can be sorted. To sort the list, you call its sort method, which will sort it in-place. Remember that in-place means that sort does not return anything. It always returns None. Both the sort method and the sorted function will also allow you to sort by a specified key and you can tell them to sort ascending or descending by setting its reversed flag.

List Slicing Python lists support the idea of slicing. Slicing a list is done by using square brackets and entering a start and stop value. That means you want to start at the second to last item in the list, 23, and take it to the end of the list. Copying a List Occasionally you will want to copy a list. What that means is that if you were to have mutable objects in your list, they can be changed and it will affect both lists. For example, if you had a dictionary in your list and the dictionary was modified, both lists will change, which may not be what you want.

You will learn about dictionaries in chapter 8. To avoid running into weird issues where changing one list affects the copied list, you should use the deepcopy method from the copy module instead. You will be using lists extensively when you are programming in Python. How do you create a list? Create a list with 3 items and then use append to add two more.

What is wrong with this code? How do you remove the 2nd item in this list? Create a list that looks like this: [4, 10, slicing to get only the middle 3 items. Tuples consist of a number of values that are separated by commas. A tuple is immutable whereas a list is not. Immutable means that the tuple has a fixed value and cannot change. You cannot add or delete items in a tuple. Immutable objects are useful when you need a constant hash value.

The most popular example of a hash value in Python is the key to a Python dictionary, which you will learn about in chapter 8. Creating Tuples You can create tuples in several different ways. Those values could be integers, lists, dictionaries, or any other object. Working With Tuples There are not many ways to work with tuples due to the fact that they are immutable. Tuples are zero-indexed, meaning that the first element starts at zero. However, this causes a TypeError to be raised because tuples are immutable and cannot be changed.

The id function returns the id of the object. The ID number changed after concatenating the second tuple. That means that you have created a new object. Special Case Tuples There are two special-case tuples. A tuple with zero items and a tuple with one item. The reason they are special cases is that the syntax to create them is a little different. Note the trailing comma after the 2 in the example above. While the parentheses are usually optional, I highly recommend them for single-item tuples as the comma can be easy to miss.

Wrapping Up The tuple is a fundamental data type in Python. It is used quite often and is certainly one that you should be familiar with. You will be using tuples in other data types. You will also use tuples to group related data, such as a name, address and country.

In this chapter, you learned how to create a tuple in three different ways. You also learned that tuples are immutable. Finally, you learned how to concatenate tuples and create empty tuples. Now you are ready to move on to the next chapter and learn all about dictionaries! How do you create a tuple?

Can you show how to access the 3rd element in this tuple? Is it possible to modify a tuple after you create it? Why or why not? How do you create a tuple with a single item? A dictionary is a key, value pair. Some programming languages refer to them as hash tables. They are described as a mapping that maps keys hashable objects to values any object.

Immutable objects are hashable immutable means unable to change. Starting in Python 3. What that means is that when you add a new key, value pair to a dictionary, it remembers what order they were added. Prior to Python 3. Creating Dictionaries You can create a dictionary in a couple of different ways. The most common method is by placing a comma-separated list of key: value pairs within curly braces.

You will learn more about these when you learn about functions. You can think of keyword arguments as a series of keywords with the equals sign between them and their value. The second example shows you how to create a list that has 3 tuples inside of it.

Then you pass that list to dict to convert it to a dictionary. You can access any value in a dictionary via the key. If the key is not found, you will receive a KeyError. Dictionary Methods As with most Python data types, dictionaries have special methods you can use. It optionally allows you to return a default if the key is not found.

The default for that value is None. In that case, it returns None. You may remember this issue being mentioned back in the chapter on lists. Then pop is the method for you. The pop method takes a key and an option default string. The pairs are returned in last-in first-out LIFO order, which means that the last item added will also be the first one that is removed when you use this method.

If called on an empty dictionary, you will receive a KeyError. The other can be another dictionary, a list of tuples, etc. You can also use the update method from the previous section to modify your dictionary. Wrapping Up The dictionary data type is extremely useful. You will find it handy to use for quick lookups of all kinds of data. You can set the value of the key: value pair to any object in Python. So you could store lists, tuples, and other objects as values in a dictionary.

You learned the following topics in this chapter: Creating dictionaries Accessing dictionaries Dictionary methods Modifying dictionaries Deleting items from your dictionary It is fairly common to need a dictionary that will create a key when you try to access one that does not exist. It has a defaultdict class that is made for exactly that use case. How do you create a dictionary?

You have the following dictionary. Using the dictionary above, how would you remove the email field from the dictionary? How do you get just the values from a dictionary? You can use a set for membership testing, removing duplicates from a sequence and computing mathematical operations, like intersection, union, difference, and symmetric difference.

Due to the fact that they are unordered collections, a set does not record element position or order of insertion. Because of that, they also do not support indexing, slicing or other sequence-like behaviors that you have seen with lists and tuples. There are two types of set built-in to the Python language: set - which is mutable frozenset - which is immutable and hashable This chapter will focus on set.

Creating a Set Creating a set is pretty straight-forward. You can create them by adding a series of comma-separated objects inside of curly braces or you can pass a sequence to the built-in set function. Note that instead of key: value pairs, you have a series of values. When you print out the set, you can see that duplicates were removed automatically. If there had been any duplicates in the list, they would have been removed.

Instead, you need to iterate over a set. You can do that using a loop, such as a while loop or a for loop. You can access items in sets much faster than lists.

A Python list will iterate over each item in a list until it finds the item you are looking for. When you look for an item in a set, it acts much like a dictionary and will find it immediately or not at all. Changing Items While both dict and set require hashable members, a set has no value to change.

However, you can add items to a set as well as remove them. You were able to add an item to the set by passing it into the add method. So it could take, for example, a list, tuple or another set. Removing Items You can remove items from sets in several different ways. KeyError: 'pop from an empty set' This is very similar to the way that pop works with the list data type, except that with a list, it will raise an IndexError. Clearing or Deleting a Set Sometimes you will want to empty a set or even completely remove it.

Set Operations Sets provide you with some common operations such as: union - Combines two sets and returns a new set intersection - Returns a new set with the elements that are common between the two sets difference - Returns a new set with elements that are not in the other set These operations are the most common ones that you will use when working with sets. The union method is actually kind of like the update method that you learned about earlier, in that it combines two or more sets together into a new set.

Then you use union on the first set to add the second set to it. It creates a new set. So when you call intersection , it returns a new set with a single element in it.

There are other methods that you can use with sets, but they are used pretty infrequently. You should go check the documentation for full details on set methods should you need to use them. Wrapping Up Sets are a great data type that is used for pretty specific situations.

You will find sets most useful for de-duplicating lists or tuples or by using them to find differences between multiple lists. In this chapter, you learned about the following: Creating a set Accessing set members Changing items Adding items Removing items Deleting a set Any time you need to use a set-like operation, you should take a look at this data type.

However, in all likelihood, you will be using lists, dictionaries, and tuples much more often. How do you create a set? How do you add an item to a set? How do you find the common items between two sets?

For example, you might want to know if someone is old enough to create a bank account. If they are, that is usually represented as True.

These values are known as Booleans or bool for short. In Python, False maps to 0 zero and True maps to 1 one. It assigns the value on the right to the variable on the left. The bool Function Python also provides the bool function, which allows you to cast other types to True or False. But wait, that third one is a string with a zero in it and it returned True as well!

What that means is that when you are dealing with non-Numeric types, True will map to sequences with one or more items and False will map to sequences with zero items. In this case, the string, '0', has one character, so it maps to True. Empty lists and dictionaries map to False, while lists and dictionaries with one or more items map to True. Integers or floats that are 0 or 0. What About None? None is a keyword in Python and its data type is NoneType.

None is not the same as 0, False or an empty string. You will learn more about why this is important in the next chapter. Wrapping Up The bool or Boolean type is important in programming as it a very simple way to test if something is True or False. You will be using the Boolean values True and False, as well as None, often when you are programming in Python. What number does True equal?

How do you cast other data types to True or False? Chapter 11 - Conditional Statements Developers have to make decisions all the time. How do you approach this problem?

Do you use technology X or technology Y? Which programming language s can you use to solve this? Your code also sometimes needs to make a decision. Here are some common things that code checks every day: Are you authorized to do that?

Is that a valid email address? Is that value valid in that field? These sorts of things are controlled using conditional statements. This topic is usually called control flow.

In Python, you can control the flow of your program using if, elif and else statements. You can also do a crude type of control flow using exception handling, although that is usually not recommended. Some programming languages also have switch or case statements that can be used for control flow. Python does not have those. Comparison Operators Before you get started using conditionals, it will be useful to learn about comparison operators.

Comparison operators let you ask if something equals something else or if they are greater than or less than a value, etc. You are logged in In this example, you create a variable called authenticated and set it to True. A conditional statement in Python takes this form: 1 if : 2 do something here To create a conditional, you start it with the word if, followed by an expression which is then ended with a colon.

When that expression evaluates to True, the code underneath the conditional is executed. Indentation Matters in Python Python cares about indentation. A code block is a series of lines of code that is indented uniformly. Python determines where a code block begins and ends by this indentation. Other languages use parentheses or semi-colons to mark the beginning or end of a code block. Indenting your code uniformly is required in Python.

If you do not do this correctly, your code will not run as you intended. One other word of warning. Do not mix tabs and spaces. IDLE will complain if you do and your code may have hard-to-diagnose issues. The Python style guide PEP8 recommends using 4 spaces to indent a code block. You can indent your code any number of spaces as long as it is consistent. However, 4 spaces are usually recommended.

If authenticated had been set to False, then nothing would have been printed out. This code would be better if you handled both conditions though. Branching Conditional Statements You will often need to do different things depending on the answer to a question.

In a real program, you would have more than just a print statement. You would have code that would redirect the user to the login page or, if they were authenticated, it would run code to load their inbox. So the code here is checking the age against different hard-coded values. If the age is less than 18, then the citizen can follow the elections on the news. If they are older than 18 but less than 35, they can vote in all elections.

Then they can run for any office themselves and participate in their democracy as a politician. Nesting Conditionals You can put an if statement inside of another if statement. This is known as nesting. If the age is greater than a certain value, then it falls into the first code block and will execute the nested if statement, which checks the car type.

If the age is less than an arbitrary amount then it will simply print out a message. Theoretically, you can nest conditionals any number of times. However, the more nesting you do, the more complicated it is to debug later. You should keep the nesting to only one or two levels deep in most cases.

Fortunately, logical operators can help alleviate this issue! Logical Operators Logical operators allow you to chain multiple expressions together using special keywords.

Pro Python System Administration, 2nd Edition explains and shows how to apply Python scripting in practice. It will show you how to approach and resolve real-world issues that most system Python Cookbook, 2nd Edition. Python Network Programming Cookbook, 2nd Edition - You can run commands, install packages, or set up new websites remotely from your laptop.

Privacy Policy. New eBooks. Search Engine. It will show you how to approach and resolve real-world issues that most system administrators will come across in their careers. This book has been updated using Python 2. It also uses various new and relevant open source projects and tools that should now be used in practice. In this updated edition, you will find several projects in the categories of network administration, web server administration, and monitoring and database management.

In each project, the author will define the problem, design the solution, and go through the more interesting implementation steps. Each project is accompanied by the source code of a fully working prototype, which you'll be able to use immediately or adapt to your requirements and environment. This book is primarily aimed at experienced system administrators whose day-to-day tasks involve looking after and managing small-to-medium-sized server estates.

It will also be beneficial for system administrators who want to learn more about automation and want to apply their Python knowledge to solve various system administration problems. Python developers will also benefit from reading this book, especially if they are involved in developing automation and management tools. The basic knowledge of installing packages on various operating systems is discussed.



0コメント

  • 1000 / 1000