code-formatting guideline. A code style guide provides recommendations to
improve the readability and consistency of your Python code. It makes it eas-
ier for you to understand your own code when you read it later or for others if
6
Chapter 1
you decide to share it. The Python community has a such a guideline, called
PEP 8. You can read the full PEP 8 guide here: https://www.python.org/dev/peps/
pep-0008/.
The examples in this book generally follow PEP 8, with a few differ-
ences. You’ll see that the code in this book follows a pattern like this:
1 from lxml import etree
from subprocess import Popen
2 import argparse
import os
3 def get_ip(machine_name):
pass
4 class Scanner:
def __init__(self):
pass
5 if __name__ == '__main__':
scan = Scanner()
print('hello')
At the top of our program, we import the packages we need. The first
import block 1 is in the form of
from
XXX import
YYY
type. Each import line
is in alphabetical order.
The same holds true for the module imports—they, too, are in alphabet-
ical order 2. This ordering lets you see at a glance whether you’ve imported a
package without reading every line of imports, and it ensures that you don’t
import a package twice. The intent is to keep your code clean and lessen the
amount you have to think when you reread your code.
Next come the functions 3, then class definitions 4, if you have any.
Some coders prefer to never have classes and rely only on functions. There’s
no hard-and-fast rule here, but if you find you’re trying to maintain state
with global variables or passing the same data structures to several func-
tions, that may be an indication that your program would be easier to
understand if you refactor it to use a class.
Finally, the main block at the bottom 5 gives you the opportunity to use
your code in two ways. First, you can use it from the command line. In this
case, the module’s internal name is
__main__
and the main block is executed.
For example, if the name of the file containing the code is scan.py, you could
invoke it from the command line as follows:
python scan.py
This will load the functions and classes in scan.py and execute the main
block. You would see the response
hello
on the console.
Second, you can import your code into another
program with no side
effects. For example, you would import the code with
import scan
Black Hat Python (Early Access) © 2021 by Justin Seitz and Tim Arnold
Setting Up Your Python Environment
7
Since its internal name is the name of the Python module,
scan
, and not
__main__
, you have access to all the module’s defined functions and classes,
but the main block is not executed.
You’ll also notice we avoid variables with generic names. The better
you get at naming your variables, the easier it will be to understand the
program.
You
should have a virtual machine, Python 3, a virtual environment,
and an IDE. Now let’s get into some actual fun!
Black Hat Python (Early Access) © 2021 by Justin Seitz and Tim Arnold