- The Python Workshop
- Andrew Bird Dr Lau Cher Han Mario Corchero Jiménez Graham Lee Corey Wade
- 1917字
- 2021-06-11 12:51:30
Python Scripts and Modules
In previous chapters, you have been executing Python in an interactive Python console or a Jupyter Notebook. However, you may be aware that most Python code lives in text files with a .py extension. These files are simply plain text and can be edited with any text editor. Programmers typically edit these files using either a text editor such as Notepad++, or Integrated Development Environments (IDEs) such as Jupyter or PyCharm.
Typically, standalone .py files are either called scripts or modules. A script is a file that is designed to be executed, usually from the command line. On the other hand, a module is usually imported into another part of the code or an interactive shell to be executed. Note that this is not a hard distinction; modules can be executed, and scripts can be imported into other scripts/modules.
Exercise 34: Writing and Executing Our First Script
In this exercise, you will create a script called my_script.py and execute it on the command line. You will be then finding the sum of the factorials of three numbers:
- Using your favorite text editor, create a new file called my_script.py. You can also use Jupyter (New | Text File).
- Import the math library:
import math
- Suppose that you had a list of numbers and you wanted to print the sum of the factorials of these numbers. Recall that a factorial is the product of all the integers up to and equal to a given number.
For instance, the factorial of 5 is calculated as 5! = 5 * 4 * 3 * 2 * 1 = 120.
In the following code snippet, you are going to find the sum of factorials of 5,7 and 11.
numbers = [5, 7, 11]
- Using the math.factorial function and list comprehension, compute and print result:
result = sum([math.factorial(n) for n in numbers])
print(result)
- Save the file.
- Open a Terminal or a Jupyter Notebook and ensure that your current directory is the same as the one with the my_script.py file. To check this, if you run dir in the Terminal, you should see my_script.py in the list of files. If not, navigate to the correct directory using the cd command.
- Run python my_script.py to execute your script.
You should get the following output:
39921960
In this exercise, you successfully created and executed a file by navigating to the correct directory from the Terminal or Jupyter Notebook.
Exercise 35: Writing and Importing Our First Module
In this exercise, as in Exercise 34, Writing and Executing Our First Script, you will be finding the factorials of three numbers. However, you will now create a module called my_module.py, and import it into a Python shell:
- Using your favorite text editor, create a new file called my_module.py. You can also use Jupyter (New | Text File).
- Add a function that prints the result of the computation in Exercise 34, Writing and Executing Our First Script. You will learn more about this function notation in the upcoming section on basic functions:
import math
def compute(numbers):
return([math.factorial(n) for n in numbers])
- Save the file.
- Open a Python shell or Jupyter Notebook and execute the following:
from my_module import compute
compute([5, 7, 11])
You should get the following output:
[120, 5040, 39916800]
Note
Writing this code as a module is useful if you want to reuse our welcome function in another script or module. However, if you just want to execute the print statement once, and you don't want to have to import our function to a shell, the script is more convenient.
In this exercise, you created a module file called my_module.py and imported this module file to get the expected output on Jupyter or the Python shell.
Shebangs in Ubuntu
The first line of a Python script will often be:
#!/usr/bin/env python
As additional information, if you are using a Windows operating system, you can ignore this line. However, it is worth understanding its function. This path specifies the program that the computer should use to execute this file. In the previous example, you had to tell the Command Prompt to use Python to execute our my_script.py script. However, on UNIX systems (such as Ubuntu or macOS X), if your script has a shebang, you can execute it without specifying that the system should use Python. For example, using Ubuntu, you will simply write:

Figure 3.1: Executing a script with a shebang statement in a UNIX system
Docstrings
A docstring which was mentioned in the Chapter 1, Vital Python: Math, Strings, Conditionals, and Loops is a string appearing as the first statement in a script, function, or class. The docstring becomes a special attribute of the object, accessible with __doc__. Docstrings are used to store descriptive information to explain to the user what the code is for, and some high-level information on how they should use it.
Exercise 36: Adding a Docstring to my_module.py
In this exercise, you extend our my_module.py module from Exercise 35, Writing and Importing Our First Module, by adding a docstring:
- Open my_module.py in Jupyter or a text editor.
- Add a docstring to the script (as the first line before beginning with your code as mentioned in the following code snippet):
""" This script computes the sum of the factorial of a list of numbers"""
- Open a Python console in the same directory as your my_module.py file.
- Import the my_module module:
import my_module
- Call the help function on our my_module script to view the docstring. The help function can be used to obtain a summary of any available information regarding a module, function, or class in Python. You can also call it without an argument, that is, as help(), to start an interactive series of prompts:
help(my_module)
You should get the following output:
Figure 3.2: The output of the help function
- View the __doc__ property of my_module as a second way of viewing the docstring:
my_module.__doc__
You should get the following output:

Figure 3.3: Viewing the docstring
Docstrings can span one line, such as in the preceding example, or multiple lines. The following is an example of a Docstring:
"""
This script computes the sum of the factorial of a list of numbers.
"""
Imports
After the optional shebang statement and docstring, Python files typically import classes, modules, and functions from other libraries. For example, if you wanted to compute the value of exp(2), you could import the math module from the standard library (you will learn more about the standard library in Chapter 6, The Standard Library):
import math
math.exp(2)
You should get the following output:
7.38905609893065
In the preceding example, you imported the math module and called an exp function that exists within the module. Alternatively, you could import the function itself from the math module:
from math import exp
exp(2)
You should get the following output:
7.38905609893065
Note that there is a third way of importing, which should generally be avoided unless necessary:
from math import *
exp(2)
You should get the following output:
7.38905609893065
The import * syntax simply imports everything in the module. It is considered undesirable primarily because you end up with references to too many objects, and there's a risk that the names of these objects will clash. It's also harder to see where certain objects are imported from if there are multiple import * statements.
You can also rename modules or imported objects in the import statement itself:
from math import exp as exponential
exponential(2)
You should get the following output:
7.38905609893065
This is sometimes useful if you simply find the name of the object to be unwieldy, making your code less readable. Or, it could be necessary where you want to use two modules that happen to have the same name.
Exercise 37: Finding the System Date
In this exercise, you write a script that prints the current system date to the console by importing the datetime module:
- Create a new script called today.py in the Python Terminal.
- Add a docstring to the script:
"""
This script prints the current system date.
"""
- Import the datetime module:
import datetime
- Print out the current date using the now() property of datetime.date:
print(datetime.date.today())
- Run the script from the command line as shown in the Figure 3.4.

Figure 3.4: The command-line output
In this exercise, you were able to write a script that prints the date and time using the datetime module. Hence, you can see how modules can be helpful.
The if __name__ == "__main__" Statement
You will often see this cryptic statement in Python scripts. You won't cover this concept in-depth, but it's worth understanding. It is used when you want to be able to execute the script by itself, but also be able to import objects from the script as though it were a regular module.
For example, suppose you wanted to get the sum of the numbers from 1 to 10. If you execute the function from the command line, you want the result printed to the console. However, you also want to be able to import the value to use it elsewhere in our code.
You may be tempted to write something like this:
result = 0
for n in range(1, 11): # Recall that this loops through 1 to 10, not including 11
result += n
print(result)
If you execute this program from the command line, it will print the output 55, as expected. However, if you try importing the result in a Python console, it will print the result again. When importing the result, you just want the variable; you don't expect it to print to the console:
from sum_to_10 import result
You should get the following output:
55
To fix this, you only call the print function in the case where __name__ == '__main__':
result = 0
for n in range(1, 11): # Recall that this loops through 1 to 10, not including 11
result += n
if __name__ == '__main__':
print(result)
When executing from the command line, the Python interpreter sets the special __name__ variable equal to the '__main__' string, such that when you get to the end of your script, the result is printed. However, when importing result, the print statement is never reached:
from sum_to_10 import result
result * 2
110
Activity 8: What's the Time?
You are asked to build a Python script that tells you the current time.
In this activity, you will use the datetime module to build the current_time.py script that outputs the current system time, and then you will import the current_time.py script into a Python console.
The steps to do this are as follows:
- Create a new script called current_time.py in Jupyter or a text editor.
- Add a docstring to the script to explain what it does.
- Import the datetime module.
- Get the current time using datetime.now().
- Print the result, but only if the script is to be executed.
- Execute the script from Command Prompt to check it prints the time.
- Import the time into a Python console and check if the console output does not print the time.
- The output from the Command Prompt will be as follows:

Figure 3.5: Printing the time to the command line
The output from a Python console should look like this:
from current_time import time
time
You should get the following output:

Figure 3.6: The output in the datetime format
Note
The solution for this activity is available on page 529.