0% found this document useful (0 votes)
191 views41 pages

01 HCIP-Datacom-Python Programming Basics Lab Guide

Uploaded by

Paterson Nguepi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views41 pages

01 HCIP-Datacom-Python Programming Basics Lab Guide

Uploaded by

Paterson Nguepi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Huawei Certification Training

HCIP-Datacom-Network Automation
Developer
Python Programming Basics
Lab Guide

V1.0

Huawei Technologies Co., Ltd.


Copyright © Huawei Technologies Co., Ltd. 2020. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com/
HCIP-Datacom-Network Automation Developer Lab Guide

Huawei Certification System


Huawei Certification follows the "platform + ecosystem" development strategy, which is a new
collaborative architecture of ICT infrastructure based on "Cloud-Pipe-Terminal". Huawei has set up
a complete certification system consisting of three categories: ICT infrastructure certification,
platform and service certification, and ICT vertical certification. It is the only certification system that
covers all ICT technical fields in the industry. Huawei offers three levels of certification: Huawei
Certified ICT Associate (HCIA), Huawei Certified ICT Professional (HCIP), and Huawei Certified ICT
Expert (HCIE). Huawei Certification covers all ICT fields and adapts to the industry trend of ICT
convergence. With its leading talent development system and certification standards, it is
committed to fostering new ICT talent in the digital era, and building a sound ICT talent ecosystem.

HCIP-Datacom-Network Automation Developer is designed for professional engineers who are


capable of network automation development. The HCIP-Datacom certification will qualify you as
professionals in network automation development, who are capable of automatic deployment,
development, and O&M of enterprise networks.

The Huawei certification system introduces the industry, fosters innovation, and imparts cutting-
edge datacom knowledge.

2021-01-20 Huawei confidential. Page 3 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

About This Document

Introduction
This document is an HCIP-Datacom-Network Automation Developer certification
training course and is intended for trainees who are going to take the HCIP-
Datacom-Network Automation Developer exam or readers who want to
understand Python programming basics and practices.

Background Knowledge Required


This course is intended for professional network automation engineers. The
trainees are supposed to have the following background knowledge:

● HCIA-Datacom

Lab Environment
Description
This lab environment is intended for datacom engineers who are preparing for the
HCIP-Datacom-Network Automation Developer exam. The experiments can be
carried out on any Python compiler, and Juypter Notebook and Pycharm are
recommended.

Compilation Environment
The compilation environment is based on the following compiler versions:

Compiler Software Version

Anaconda3 2020.02

Pycharm Community Edition 2020.01

2021-01-20 Huawei confidential. Page 4 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Contents

About This Document ............................................................................................................... 4


1 Setting up the Environment ................................................................................................ 7
1.1 Introduction to Anaconda........................................................................................................................................... 7
1.2 Installation Procedure .................................................................................................................................................. 8
1.3 Verifying the Installation .......................................................................................................................................... 13

2 Python Programming Basics ..............................................................................................15


2.1 Introduction to Experiment ...................................................................................................................................... 15
2.2 Code Practices ............................................................................................................................................................... 15
2.2.1 Python Data Types ................................................................................................................................................... 16
2.2.1.1 Data Type: Numerics ........................................................................................................................................... 16
2.2.1.2 Data Type: Strings ................................................................................................................................................ 17
2.2.1.3 Data Type: Lists ..................................................................................................................................................... 18
2.2.1.4 Data Type: Tuples ................................................................................................................................................. 19
2.2.1.5 Data Type: Dictionaries....................................................................................................................................... 19
2.2.1.6 Data Type: Sets ...................................................................................................................................................... 19
2.2.2 Deep Copy and Shallow Copy.............................................................................................................................. 20
2.2.3 if Statement................................................................................................................................................................ 20
2.2.4 Loop Statement ........................................................................................................................................................ 21
2.2.5 Customizing Functions ........................................................................................................................................... 22
2.2.6 I/O Operations........................................................................................................................................................... 23
2.2.7 Exception Handling.................................................................................................................................................. 25
2.2.8 Object-Oriented Programming (Class) ............................................................................................................ 27
2.2.8.1 Creating and Using Classes ............................................................................................................................... 27
2.2.8.2 Attributes of Class ................................................................................................................................................ 27
2.2.8.3 Encapsulating Classes.......................................................................................................................................... 28
2.2.8.4 Inheriting Classes .................................................................................................................................................. 28
2.2.8.5 Class Polymorphism ............................................................................................................................................. 29

3 Python - Advanced ...............................................................................................................31

2021-01-20 Huawei confidential. Page 5 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

3.1 Introduction ................................................................................................................................................................... 31


3.2 Code Practices ............................................................................................................................................................... 31
3.2.1 Regular Expressions ................................................................................................................................................. 31
3.2.1.1 re.match ................................................................................................................................................................... 33
3.2.1.2 re.search ................................................................................................................................................................... 33
3.2.1.3 Retrieval and Replacement ............................................................................................................................... 33
3.2.1.4 re.compile ................................................................................................................................................................ 34
3.2.1.5 findall ........................................................................................................................................................................ 34
3.2.1.6 re.split() .................................................................................................................................................................... 35
3.2.2 Decorators................................................................................................................................................................... 35
3.2.3 Generators .................................................................................................................................................................. 36
3.2.4 Iterators ....................................................................................................................................................................... 37
3.2.5 Multiple Tasks ........................................................................................................................................................... 39
3.2.5.1 Multiple Threads ................................................................................................................................................... 39
3.2.5.2 Multiple Processes ................................................................................................................................................ 41

2021-01-20 Huawei confidential. Page 6 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

1 Setting up the Environment

1.1 Introduction to Anaconda


Anaconda is a distribution of Python for scientific computing, and it supports
Linux, macOS, and Windows. It provides simplified package management and
environment management, and easily deals with the installation issues when the
system has multiple Python versions and third-party packages. Anaconda uses
Conda or Pip to implement package and environment management. It also comes
with Python and related tools. Anaconda is a Python tool for enterprise-level big
data analytics. It contains more than 720 open-source data-science packages,
including data visualization, machine learning, and deep learning. It can be used
for data analysis, big data and AI fields.

Anaconda provides the following features for developers:

● Notebook is supported, which is friendly to beginners.


● Python has been integrated into Anaconda, and there is an option to select
the Python version during download.
● You only need to add a virtual environment to Anaconda when different
frameworks are required to support development. You can conduct
development in different environments without worrying about compatibility
issues. You can also configure environments for special projects to facilitate
management.

You can also use other development environments (such as PyCharm) to run Python scripts.
PyCharm is a Python IDE that provides a set of tools to help users improve efficiency in
development using Python, such as debugging, syntax highlighting, project management,
code jumping, intelligent tips, automatic completion, unit test, and version control. In
addition, the IDE provides some advanced functions to support professional Web
development under the Django framework.

2021-01-20 Huawei confidential. Page 7 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

1.2 Installation Procedure


Step 1 Download Anaconda.

Log in to the official website of Anaconda


(https://www.anaconda.com/products/individual), and click Download to
download the installation package.

Select the version for Windows, macOS, or Linux. In this example, select Windows,
select Python 3.7 (recommended) or Python 2.7, and click 64-Bit Graphical
Installer (not supported by a 32-bit computer).

Step 2 Install Anaconda.

Double-click the Anaconda3-x.x.x-Windows-x86_64.exe file. In the dialog box


that is displayed, click Next.

2021-01-20 Huawei confidential. Page 8 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Click I Agree.

2021-01-20 Huawei confidential. Page 9 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Install for: Select Just Me and click Next.

Step 3 Specify the software installation path and click Next.

2021-01-20 Huawei confidential. Page 10 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Step 4 Configure environment variables.

Select Add Anaconda to my PATH environment variable and Register


Anaconda as my default Python 3.7 to reduce subsequent configurations, and
click Install. (Note: If Python of another version has been installed on the
computer, you are advised to remove it and install Anaconda. If it is not deleted,
you are advised to de-select the two options; otherwise, a path error may occur.)

When the installation is complete, click Next.

2021-01-20 Huawei confidential. Page 11 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Step 5 View installation information.

Click Next to view related information.

2021-01-20 Huawei confidential. Page 12 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Click Finish to view the Anaconda tutorial page.

----End

1.3 Verifying the Installation


Run the Python script.

1. Choose Start > Jupyter Notebook to display the Jupyter homepage.

2. Click New in the upper right corner of the page and select Python 3 to create
a Jupyter file.

2021-01-20 Huawei confidential. Page 13 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

The title in the red box is the default title, which can be changed if you
double-click the title.
Enter the code in the green rectangle, and click Run to run the code.

3. Enter the following code in the text box:


print('Hello World') # Print: Hello World
print("Hello World") # Print: Hello World.
#The output is the same regardless of whether single or double quotation marks are carried in input.

4. Click Run, as shown in the following figure.

2021-01-20 Huawei confidential. Page 14 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2 Python Programming Basics

2.1 Introduction to Experiment


This experiment uses independent code practices of each module to help readers
master the Python3 syntax.

● Basic data types of Python


● Deep copy and shallow copy
● Flow control
● Functions
● Operations on files
● Troubleshooting
● Object-oriented programming

It is recommended to learn this guide with the official Python Tutorial,


https://docs.python.org/3/tutorial/index.html.

2.2 Code Practices


After Anaconda3 is installed on the local PC, open Jupyter Notebook and create a
Python3 notebook file. (You can also use other compilers for the experiment, such
as Pycharm.)

2021-01-20 Huawei confidential. Page 15 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

The title in the red box is the default title, and you can double-click the title to
change the file name.

The blue box in the following figure is the code input box. After the code is
complete, click Run to run the code.

2.2.1 Python Data Types


Python has rich data types, including numerics, strings, lists, tuples, dictionaries,
and sets. This section describes the characteristics of different data types using
code practices. For details, see "Built-in Types" in the Python standard library.
https://docs.python.org/3.8/library/index.html.

2.2.1.1 Data Type: Numerics


This data type is used to store numeric values, and it is immutable, which means
that, if it is changed, a new object will be assigned.

Note that Boolean operations in Python use keywords instead of operators to


express “and/or/not”.

print(True+False) # The output is 1. By default, 1 indicates True, and 0 False.


print(True or False) # True is displayed, and the "or" operation is performed.
Print(5//2) # The output is 2, and “//” is the rounding operator.
Print(5%2) # The output is 1, and “%” is the modulo operator.
print(3**2) # The output is 9, and “**” indicates the power operation.

2021-01-20 Huawei confidential. Page 16 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

print(5+1.6) # The output is 6.6. By default, the sum of numbers in different precisions follow the highest
precision of the numbers.

2.2.1.2 Data Type: Strings


A string consists of digits, letters, and underscores (_). Objects are created using
single, double, or triple quotation marks.

Basic operations on strings:

S = 'python' # Assign ‘python’ to variable S.


# len(obj): Return the object length.
print(len(S)) # Output 6.

print(S[0],S[1],S[-1]) # Output pyn and obtain elements based on the index.


print(S+'1',S*2) # Output python1 pythonpython: merge and repeat.

Immutability of strings:

S = 'python' # Assign a value to the variable.


S[0] = 'Z' # Program exception, as the string cannot be changed.
S1 ='Z'+S[1:] # A new string, Zython, is generated and assigned to S1.
# S[1:] indicates the string following the first character, that is, ython.
print("S:%s,S1:%s"%(S,S1)) # Output S:python, S1:Zython. %s prints the character string.

Common operations on strings:

S = "python" # Assign a value to the variable.

# str.split(str="", num=-1): The string is split by separator. If the “num”argument has a value, the string is
split into num+1 substrings. The value “-1” indicates that all strings are split.
print(S.split('h')) # Output ['pyt','on'], and split the string based on “h”.

# str.replace(old, new[, max]): A string generated after “old” in the string is replaced with “new”. If the third
argument “max” is specified, this replacement can take place for not more than max times.
print(S.replace('py','PY')) # PYthon: Replace “py” in the string with “PY”.

# str.upper(): Return the value after lowercase letters are converted to uppercase letters.
print(S.upper()) # PYTHON

# str.lower(): Return the value after uppercase letters are converted to lowercase letters.
print('PYTHON'.lower()) # Output python. The string is converted into lowercase letters.

line='aa,bb,ccc,dd\n' #”\n” is a line feed character.

# str.join(sequence): “sequence” indicates a sequence to be joined. In the output, the new string generated
after the elements are specified in the sequence is returned.
print(''.join(['life', 'is' ,'short'])) # Output “life is short” and “join” joins the string.

hw12= '%s %s %d' % ('hello', 'world', 12) # Format the string.


print(hw12) # Output “hello world 12”.

2021-01-20 Huawei confidential. Page 17 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.1.3 Data Type: Lists


Lists can implement data structures of most set classes. It supports characters,
numbers, strings, and even lists (that is, nesting). It is identified by [].

● Common operations on lists:


animals = ['cat', 'dog', 'monkey'] # Define the list animals.

# list.append(obj): Add a new object to the end of the list.


animals.append(‘fish’) # Append an element.
print(animals) # Output ['cat', 'dog', 'monkey', 'fish'].

# list.remove(obj): Remove the first match for a value in the list.


animals.remove(‘fish’) # Delete the element “fish”.
print(animals) # Output ['cat', 'dog', 'monkey'].

# list.insert(index, obj): Insert a specified object to a specified position in the list. The index indicates
the position.
animals.insert(1,’fish’) # Insert the element “fish” at the position of subscript 1.
print(animals) # Output ['cat', 'fish', 'dog', 'monkey'].

# list.pop([index=-1]): Remove the element (the last element by default) corresponding to the
subscript in the list. The index indicates the subscript.
animals.pop(1) # Delete the element whose subscript is 1.
print(animals) # Output ['cat', 'dog', 'monkey'].

● Traverse and obtain the elements and indexes.


# enumerate(sequence): Return an index sequence consisting of a data object that can be traversed
and list the data and subscripts. This function is usually used in the “for” loop.
for i in enumerate(animals):
print(i) # Index formed by element subscripts and elements.

Output:
(0, cat)
(1, dog)
(2, monkey)

● List derivations
squares = [x*2 for x in animals] # Generate a list of elements that comply with rules in batches.
print(squares) # ['catcat ', 'dogdog ', 'monkeymonkey ']

● Sorting
list.sort(cmp=None, key=None, reverse=False): The “cmp” parameter is
optional. If it is specified, the method of this parameter is used for sorting.
“key” is an element used for comparison. “reverse” indicates the sorting rule,
and “False” indicates the ascending order.
list1 = [12,45,32,55] # Define a new list, list1.
list1.sort() # Sort the list.
print(list1) # Output [12,32,45,55].

# list.reverse(): Element in the reverse list.


list1.reverse() # Reverse the list.
print(list1) # Output [55,45,32,12]

2021-01-20 Huawei confidential. Page 18 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.1.4 Data Type: Tuples


A tuple is identified by () and internal elements are separated by commas (,).

A tuple cannot be assigned a value for a second time, which is similar to a read-
only list.

Common operations on tuples:

T=(1,2,3) # Create a tuple.


print(T+(4,5)) # Combine tuples and output (1, 2, 3, 4, 5).
t=(42,) # A tuple with only one element, which is different from a number.
tuple1 = (12,45,32,55,[1,0,3]) # Create a tuple.
tuple1[0] = "good" # Program exception, as the tuple is immutable and a value cannot be
assigned to it.
tuple1[4][0] = 2 # Values cannot be assigned to mutable elements. In the example, the
elements are in the [1,0,3] list.
print(tuple1) # (12,45,32,55,[2,0,3])

2.2.1.5 Data Type: Dictionaries


A dictionary is a flexible built-in data structure and is identified by {}.

A dictionary consists of indexes (keys) and their values. Compared with a list,
elements in a dictionary are saved as keys instead of offsets.

Common operations on dictionaries:

# Three operations to assign values to dictionaries:


x = {'food':'Spam','quantity':4,'color':'pink'}
x = dict(food='Spam',quantity=4, color='pink')
x = dict([("food", "Spam"),("quantity", "4"),("color","pink")])

# dict.copy(): Copy data.


d =x.copy()
d['color'] = 'red'
print(x) # {'food':'Spam','quantity':4,'color':'pink'}
print(d) # {'food':'Spam','quantity':4,'color':'red'}

# Element access.
print(d['name']) # Error information is obtained.
print(d.get('name')) # Output none.
print(d.get('name','The key value does not exist.')) # Output “The key value does not exist”.
print(d.keys()) # Output “dict_keys(['food', 'quantity', 'color'])”.
print(d.values()) # Output “dict_values(['Spam', 4, 'red'])”.
print(d.items()) # Output “dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'red')])”.
d.clear() # Clear all data in the dictionary.
print(d) # Output “{}”.
del(d) # Delete the dictionary.

2.2.1.6 Data Type: Sets


A set is an unordered sequence of unrepeatable elements. Sets can be created
using braces {} or the set() function.

2021-01-20 Huawei confidential. Page 19 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Common operations on sets:

sample_set = {'Prince', 'Techs'}


print('Data' in sample_set) # Output “False”. “in” is used to check whether an element exists in the set.

# set.add(obj): Add an element to a set. If the element to be added already exists in the set, no operation is
performed.
sample_set.add('Data') # Add element “Data” to the set.
print(sample_set) # Output “{'Prince', 'Techs', 'Data'}”.
print(len(sample_set)) # Output “3”.

# set.remove(obj): Remove a specified element from a set.


sample_set.remove('Data') # Delete element “Data”.
print(sample_set) # {'Prince', 'Techs'}

list2 = [1,3,1,5,3]
print(list(set(list2))) # Output [1,3,5]. The unique set elements are used to de-duplicate the list.
print(list(set(list2))) # Output the [1,3,5] list.
sample_set = frozenset(sample_set) # Immutable set.

2.2.2 Deep Copy and Shallow Copy


In Python, value assignment to an object is actually a reference to the object.
When an object is created and assigned to another variable, Python does not copy
the object but copies its reference.

In this experiment, the copy module in Python is used to differentiate deep copy
from shallow copy.

import copy # The current program calls the copy module.


Dict1 = {'name':'lee', 'age':89, 'num':[1,2,8]} # Create a dictionary.
Dict_copy = Dict1.copy() # Shallow copy.
Dict_dcopy = copy.deepcopy(Dict1) # Deep copy.
Dict2=Dict1 # Shallow copy. Directly assign a value to the object.
Dict1['num'][1] = 6 # Change the value of the nested list in the original data.
print('Dict1:'+str(Dict1)+"\n",'Dict_copy:'+ str(Dict_copy)+"\n",'Dict_dcopy:'+ str(Dict_dcopy)+
"\n",'Dict2:'+str(Dict2))

Output:

Dict1:{‘name’:’lee’, ‘age’:89, ‘num’:[1,6,8]}


Dict_copy :{'name':'lee', 'age':89, 'num':[1,6,8]} # Shallow copy modifies data..
Dict_dcopy :{'name':'lee', 'age':89, 'num':[1,2,8]} # Deep copy does not modify data.
Dict2:{'name': 'lee', 'age': 89, 'num': [1, 6, 8]} # Value assignment to an object is shallow copy, and
data is modified.

2.2.3 if Statement
The programming language provides various control structures, which allow more
complex execution paths. if statement is one of the control structures, and is used
to execute subsequent instructions after a condition is matched.

2021-01-20 Huawei confidential. Page 20 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

In this example, a Python script is compiled to receive a score entered by a user


and determine the level of the score. You can use if statement in Python to
implement this function.

# Determine the level of entered score.


# input(): Receive input data.
score = input("Please enter your score.") # The input function receives input, which is a string.

# try: except Exception: … is a Python statement used to capture exceptions. If an exception occurs in the
statement in “try”, the statement in “except “is executed.
try:
score = float(score) # Convert the score to a number.
if 100>=score>=90: # Check whether the entered value is greater than the score of a
level.
print("Excellent") # Generate the level when conditions are met.
elif 90 > score >= 80:
print("good")
elif 80>score>=60:
print("medium")
elif 60>score>=0:
print("bad")
else:
raise
except Exception:
print("Enter a correct score.")

2.2.4 Loop Statement


A loop statement can execute a statement or statement group multiple times. This
example describes two types of loops: for and while.

● for loop
The for loop can traverse any sequence of items, such as a list or string.
In this example, a Python script is compiled to print the multiplication table.
for i in range(1,10): # Define the outer loop.
for j in range(1,i+1): # Define the inner loop.
print ("%d * %d = %2d" % (i, j, i*j), end=" \t ") # Print a string in format to align the print.
print() # The “end” attribute sets the end symbol of the print, which is /n by default.

Output:
1*1= 1
2*1= 2 2*2= 4
3*1= 3 3*2= 6 3*3= 9
4*1= 4 4*2= 8 4*3=12 4*4=16
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

● while loop

2021-01-20 Huawei confidential. Page 21 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

In Python programming, the while statement is used to cyclically execute a


program. That is, under a certain condition, a program is cyclically executed
to process the same task that needs to be repeatedly processed.
When the condition is met, the statement is executed cyclically. To end the
loop, use break or continue.
# while loop
i=0 # Create the variable i.
while i<9: # Set a condition for the loop.
i+=1 # The value of i increases by 1 in each loop.
if i == 3: # Check whether the conditions are met.
print("End the current loop.")
continue # execute “continue” to end the current loop.
if i == 5:
print("End the current big loop.")
break # End the current big loop.
print(i)

Output:
1
2
End the current loop.
4
End the current big loop.

2.2.5 Customizing Functions


A function is a piece of code, organized and reusable. It can improve code
utilization and modularity of the program. Python provides many built-in
functions, such as print(). You can also create functions, that is, user-defined
functions.

This section describes how to customize functions.

● Define a function.
Use the “def” keyword to define a function, which can call the function (print
information).
def Print_Hello(): # Function name, no input value.
print("Hello, Python.") # Output
Print_Hello() # Call function.

Output:
Hello, Python.

● Parameter transfer for a function and default parameters


A function can be customized to print parameters transferred in different
ways.
def hello(greeting='hello',name='world'): # Set default parameters.
print('%s, %s!' % (greeting, name)) # Format the output.
hello() #hello, world. If no parameter is specified, the default parameter is used.
Hello ('Greetings') # Greetings, world. This is a position parameter.
hello(name=’Huawei’) # hello, Huawei. This is a keyword parameter.

2021-01-20 Huawei confidential. Page 22 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Hello ('Greetings', 'universe') # Greetings, universe. This is a position parameter.

Output:
hello, world!
Greetings, world!
hello, Huawei!
Greetings, universe!

● Length-variable parameters
A function with length-variable parameters can process parameters more
than defined. In this case, * indicates a tuple-type parameter and ** indicates a
dictionary-type parameter.
def test (a, b, *c, **d):
print (a)
print (b)
print (c)
print (d)
test (1,2,3,4,5,6,x=10,y=11) # The transfered parameters are automatically distinguished as the tuple or
dictionary type.

Output:
1
2
(3, 4, 5, 6)
{'x': 10, 'y': 11}

● Returned values
The returned value of a function is the result that the function returns to the
caller after completing the method. Use the return statement.
def plus_one (number):
return int(number)+1
plus_one (10)

Output:
11

2.2.6 I/O Operations


The standard library of Python is large and provides a wide range of modules. File
I/O is one of the built-in modules. For more operations on the standard library,
see the official document at https://docs.python.org/3.8/library/index.html.

Python I/O operations are performed to read and write files. Generally, you can
use the open function to perform the operations.

File Mode Description

r Read-only, default. The file pointer is placed in the file header.

w Write-only. The file pointer is placed in the file header, and the file
overwrites the original content.

2021-01-20 Huawei confidential. Page 23 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

File Mode Description

a Append. The pointer is placed at the end of the file. If no file exists,
a file is created.

rb Read-only files in binary format, such as audio or image files.

wb Write-only files in binary format.

ab Append files in binary format.

r+ Read and write. The file pointer is placed in the file header.

w+ Read and write. If a file exists, the file will be overwritten. If no file
exists, a file is created.

a+ Append, read, and write. If no file exists, a file is created.

● Write a file
f = open("text.txt", 'w') # Open the text.txt file. If the file does not exist, a new file is created. w: write
mode
Str = input("Please enter the content to be written.") # The built-in function “input” gets the input of
the console.
f.write(Str) # Write “Str” to file f.
f.close() # Close the file.

Output:

Enter the content to be written, “Python file operation”.


The text.txt file is generated in the same directory.

● Read a file
The read method is used to read files. If read() is not specified, all content is
read.
f = open("text.txt", 'r') # r indicates that the file is read.
print(f.read(6)) # Read six characters and move the cursor six characters backward.
print(f.read()) # Read from the current position of the cursor to the end.
f.close()

Output:
Python
file operation

● Use the context manager to operate the file.


The context manager defines the scope of using the resources. Resources are
allocated at the start of the code and released at the end of the code. This

2021-01-20 Huawei confidential. Page 24 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

simplifies code and improves its readability. The context manager works with
the “with” statement. The basic syntax is as follows:
“with” context expression [“as” resource object]: # “as” indicates that the
return value of the context is assigned to the resource object.
Object operation:
with open("text1.txt", 'w') as f: # Use the “with” statement to write data to the file.
f.write("python file operation")
with open("text1.txt", 'r') as f: # Use the “with” statement to read the file content.
print(f.read())

Output:
Python file operation

There are more methods for file operations, such as reading a line of
readlines, positioning files with “tell”, and finding files with “seek”. For details,
see Python Tutorial.

2.2.7 Exception Handling


Errors that occur during program execution are called exceptions. Common
exceptions include syntax errors (SyntaxError), undeclared variables (NameError),
and access to unknown attributes (AttributeError). Python has a powerful
troubleshooting mechanism to accurately report error information, which helps
developers locate faults.

Python uses the “try-except” statement to handle exceptions. The “try” statement
is used to check exceptions, and the “except” statement to capture exceptions.

● Create exceptions.
First, let's create an exception where the divisor in a division is 0.
num1 = input('Please enter the first digit:')
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)) #%f indicates a
floating point number.

Output:
Please enter the first digit: 10
Please enter the second digit: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-10-5cc9c0d19753> in <module>
1 num1 = input('Please enter the first digit:')
2 num2 = input('Please enter the second digit:')
----> 3 print ('The first number divided by the second number is %f'%(int(num1)/int(num2)))
4
ZeroDivisionError: division by zero

The cause of exception is ZeroDivisionError. You can capture this exception


to keep the program running properly.
● Use “try-except” to generate code.

2021-01-20 Huawei confidential. Page 25 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

The “try-except” statement is used to capture the ZeroDivisionError exception


and display “The second digit cannot be 0”.
try:
num1 = input('Please enter the first digit:’)
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)))
except ZeroDivisionError:
print('The second digit cannot be 0.')

Output:
Please enter the first digit: 10.
Please enter the second digit: 0.
The second digit cannot be 0.

The exception is successfully captured. If multiple exceptions need to be


captured, you can use multiple “except” statements in parallel to capture
different exceptions.
● Capture all exceptions.
It is very difficult to define each exception. The exception class is the parent
class of all exceptions and can represent all exceptions.
try:
num1 = input('Please enter the first digit:')
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)))
except Exception as result :
print('Captured exception: %s' % result)

Output:
Please enter the first digit: hello.
Please enter the second digit: 0.
Captured exception: invalid literal for int() with base 10: 'hello'

● No exception is captured (else and finally).


If no exception is captured in the program, the program executes the “else”
statement. Sometimes this capture operation has to be terminated regardless
of whether an exception has been caught or not. In this case, the “finally”
statement can be used.
In Python, the complete exception handling format is as follows:
try:
# Statement
except:
# Code with exception
except:
# Another code with exception
else:
# Code without exception
finally:
# Code that must be executed at last, regardless of exception

2021-01-20 Huawei confidential. Page 26 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.8 Object-Oriented Programming (Class)


Class and object are important concepts in object-oriented programming. An
object is specific and a class is general to regard a group of objects with the same
characteristics and behavior.

For example, in the first case, Dog is a class and Husky is an object of the class.
Husky has all the features and behaviors of the Dog class.

2.2.8.1 Creating and Using Classes


Create the Dog class.

Each instance created based on the Dog class stores the name and age. We will
give each dog the sit () and roll_over () abilities.

class Dog(): # Use the keyword class to declare a class.


"””Simulate dog behavior (method)"””
def sit(self): # Use a function to define the method of a class. “self”
indicates itself and is always the first parameter.
"""Simulate a dog sitting when ordered"""
print("Dog is now sitting") # In the method, “self” is used to access the name attribute.
def roll_over(self):
"""Simulate a dog rolling over when ordered."""
print("Dog rolled over!")
dog = Dog() # Create an object and use Dog to save its reference.
dog.name = "Husky" # Add an attribute that indicates the name, which is Husky.
dog.sit() # Call the method.
dog.roll_over()
print (dog.name)

Output:

Dog is now sitting


Dog rolled over!
Husky

2.2.8.2 Attributes of Class


In the previous case, if you want to create an object of the Dog class, you need to
use “object name.attribute name” again, which is troublesome. To solve this
problem, Python provides a constructor method __init__ (with two underscores
before and after) to initialize the class.

In this example, the name and age attributes are initialized to the Dog class.

class Dog(): # Use the keyword class to declare a class.


"Simulate the attributes and behaviors of dog (method)"
def __init__ (self,name,age): # Initialize class attributes. The first parameter is always self, indicating the
object itself.
"""Initialize the name and age attributes."""
self.name = name
self.age = age
def sit(self): # Use the function to define a method for class to carry the self parameter.
"""Simulate a dog sitting when ordered."""

2021-01-20 Huawei confidential. Page 27 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

self.name+" is now sitting") # The method uses “self” to access the name attribute.
def roll_over(self):
"""Simulate a dog rolling over when ordered."""
print(self.name+" rolled over!")
dog = Dog("Husky",2) # Create an object and use Dog to save its reference.
print (dog.age) # Access attributes.
dog.sit() # Call the method.
dog.roll_over()

Output:

2
Husky is now sitting
Husky rolled over!

2.2.8.3 Encapsulating Classes


The process of hiding the details of properties, methods, and method
implementations is called encapsulation. Attributes are defined as private to
prevent unauthorized value assignment.

Private attributes are implemented by __ (two underscores).

class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age # Set age to a private attribute __age.
def get_age(self):
return self.__age
dog = Dog ("Husky",2)
print (dog.name)
dog.get_age() # Call the get_age() method and return parameters.
print (dog.__age) # The program reports an error, indicating that the __age attribute does not exist
and cannot be directly called by external systems.

Output:

Husky
2
AttributeError Traceback (most recent call last)
<ipython-input-23-374e764e1475> in <module>
5 dog = Dog('Husky', '2')
6 print (dog.name)
----> 7 print (dog.__age)
8
AttributeError: 'Dog' object has no attribute '__age'

2.2.8.4 Inheriting Classes


One of the main benefits of object-oriented programming is code reuse, which is
achieved through inheritance. Inheritance can be understood as the type and
subtype relationships between classes.

In this example, the subclass Husky of class Dog is constructed to inherit the
attributes and methods of the parent class. The method of subclass (parent class)

2021-01-20 Huawei confidential. Page 28 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

is used. If a subclass needs to inherit multiple classes, the method is subclass


(parent class 1, parent class 2). In this example, a subclass inherits one class.

class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age # Set age as a private attribute __age.
def get_age(self):
return self.__age
class Husky(Dog): # Declare a subclass Husky and a parent class Dog.
pass
mydog = Husky('Larry','3') # The subclass inherits the construction method of the parent class.
print (mydog.name) # The subclass inherits the name attribute of the parent class, but cannot inherit private
attributes.
mydog.get_age() # The subclass inherits the get_age() method of the parent class.

Output:

Larry
3

2.2.8.5 Class Polymorphism


In Python, polymorphism refers to the use of objects without considering object
types. Python does not care about whether an object is a parent class or subclass,
but only cares about the behavior (method) of the object.

In this example, the parent class is Dog and has the shout method. The subclasses
of Dog, Husky and Tibetan Mastiff, rewrite the shout method of the parent class.
A function sound can be defined. When calling the shout method, the program
does not care whether the object is a parent class or subclass, but cares only
whether they all have the shout method.

# The parent class is Dog and the sound is Dog shouts.


class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def shout(self):
print ('Dog shouts')

# The subclass is Husky, shouting as woo.


class Husky(Dog):
def shout(self):
print('woo')

# The subclass is Tibetan Mastiff, shouting as barking.


class Tibetan_Mastiff(Dog):
def shout(self):
print('barking')

# Define a function sound to call the shout method.


def sound(dog):

2021-01-20 Huawei confidential. Page 29 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

dog.shout()

# dog1 is the object of Husky.


dog1 = Husky('Larry',3)
sound(dog1)

# dog2 is the object of Dog.


dog2=Dog('Richard',2)
sound(dog2)

# dog3 is the object of Tibetan Mastiff.


dog3= Tibetan_Mastiff('Sylvia',4)
sound(dog3)

Output:

Woo
Dog shouts
Barking

2021-01-20 Huawei confidential. Page 30 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

3 Python - Advanced

3.1 Introduction
This experiment uses independent code practices of each module to help readers
master the advanced Python3 syntax.

● Regular expressions
● Decorators
● Iterators
● Generators
● Multiple tasks

3.2 Code Practices


3.2.1 Regular Expressions
A regular expression is a special character sequence that helps you easily check
whether a string matches a pattern. In Python, the re module is used to
implement the regular expression function.

Table 3-1 Basic regular expression syntax

Symbol Implication Example

^ Start position to match a


string

$ End position to match a


string

* Zero to multiple matches

+ One or more matches (at

2021-01-20 Huawei confidential. Page 31 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Symbol Implication Example


least one match)

? Zero or one match

. Match with a single


character

| Or a|b: match with a or b

() All characters in the (abc): match with abc


parentheses are matched.

[] One character in the brackets [0-9 a-z A-Z]


is matched.

{} Limit of matches {n}: match with n characters


{n,}: match with n or more characters
{n,m}: match with n characters at
least and m characters at most

\ Escape character \*: match with the asterisk (*)

\w Match with letters and digits

\W Match with non-letters and


digits

\d Match with digits

\D Match with non-digit


characters

Table 3-2 Flags of Python regular expressions

Flag Description

re.I Case-insensitive matching

re.M Multi-line matching, which affects ^ and $.

re.S Make . match with all characters, including newline characters.

re.U Parses characters based on the Unicode character set. This flag affects
\w, \W.

This guide briefly describes how to use regular expressions. For more information,
see official documents.

2021-01-20 Huawei confidential. Page 32 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

3.2.1.1 re.match
The re.match function attempts to match a pattern from the start position of the
string. If the match is not successful, match() returns none.

Function syntax:

re.match(pattern, string, flags=0)

pattern indicates an expression matched. string indicates the object to be


matched. flags is a flag bit, for example, whether it is case sensitive. For details,
see the tutorial.

Example:

import re
print(re.match('www', 'www.huawei.com')) # Match www at the start position by default.
print(re.match('com', 'www.huawei.com')) # No match
print(re.match('.*com$','www.huawei.com')) # Match an object whose name ends with .com.

Output:

<re.Match object; span=(0, 3), match='www'>


None
<re.Match object; span=(0, 14), match='www.huawei.com'>

3.2.1.2 re.search
The re.search expression scans the entire string and returns the first successful
match.

Function syntax:

re.search(pattern, string, flags=0)

Example:

import re
print(re.search('www', 'www.huawei.com')) # Search for www from the start.
print(re.search('com', 'www.huawei.com')) # Search for com to the end.
print(re.search('.*com$','www.huawei.com')) # Match an object whose name ends with .com.
print(re.search('COM', 'www.huawei.com',re.I)) # Case insensitive.

Output:

<re.Match object; span=(0, 3), match='www'>


<re.Match object; span=(11, 14), match='com'>
<re.Match object; span=(0, 14), match='www.huawei.com'>
<re.Match object; span=(11, 14), match='com'>

3.2.1.3 Retrieval and Replacement


The re module of Python provides the re.sub expression to replace the matching
items in the string.

2021-01-20 Huawei confidential. Page 33 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Syntax:

re.sub(pattern, repl, string, count=0, flags=0)

pattern indicates regular expression, repl indicates the replacement string, which
can also be a function, and string indicates the original object for search. Count
refers to the maximum number of replacements (the value 0 indicates all).

Example:

import re
print(re.sub('^WWW','support', 'www.huawei.com',flags=re.I)) # Replace www with support.

Output:

support.huawei.com

3.2.1.4 re.compile
The compile function is used to compile regular expressions and generate a
regular expression object (pattern), which can be called by the match() and
search() functions.

The syntax format is as follows:

re.compile(pattern[, flags])

Example:

import re
pattern = re.compile('\d+') # Match with at least one digit.
print (pattern.match('www.huawei123.com')) # Check whether the header contains digits. No match.
The first digit is returned for print (pattern.search('www.huawei123.com')) # Search and return the first digit.

Output:

None
<re.Match object; span=(10, 13), match='123'>

3.2.1.5 findall
findall indicates that all substrings that match the regular expression are found in
the string and a list is returned. If no substring is found, an empty list is returned.

The syntax format is as follows:

findall(string[, pos[, endpos]])

string: the string to be matched; Pos: start position of the string, 0 as default;
Endpos: end position of the string, string length as default

Example:

import re
pattern = re.compile('\d+') # Match with at least one digit.
print(pattern.findall('www.huawei123.com \n 345')) # Search all strings.

2021-01-20 Huawei confidential. Page 34 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Output:

['123', '345']

3.2.1.6 re.split()
The split expression splits a string based on the matched substring and returns a
list. This expression is used as follows:

re.split(pattern, string[, maxsplit=0, flags=0])

pattern: regular expression; string: string to be matched; Maxsplit: maximum


splitting times, 0 as default, indicating no limit on splitting times

Example:

import re
s = re.split('\W+', 'www.huawei.com') # \W+ indicates that non-English characters and digits are split for one
or more times.
print(s)

Output:

['www', 'huawei', 'com']

3.2.2 Decorators
As essentially a Python function, a decorator is special as it returns a function. It
can extend the functionality without changing the existing function. The syntax of
a decorator starts with @. It is used as follows:

● Build an initial function.


Here is a function to output “I am learning Decorators”.
def test():
print ("I am learning Decorators.")
test()

Output:
I am learning Decorators.

● Extend functionality of the function.


Before extending functionality of the function, “I learned Python Data
Structures” has to be output.
Generally, the solution is as follows:
def test():
print ("I learned Python Data Structures.")
print ("I am learning Decorators.")

This solves the problem, but changes the existing function. If you want to
solve the problem without changing the original function, you can use a
decorator.

2021-01-20 Huawei confidential. Page 35 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

● Decorate the function using a decorator.


Define a new function decorator() whose parameter is a function and
returned value is also a function. The func() function that is used as a
parameter is executed inside the returned wrapper() function. Add @decoder
to the start of the test() function to get a new function.
def decorator(func):
def wrapper():
print ("I learned Python Data Structures.")
func()
return wrapper
@decorator
def test():
print ("I am learning Decorators.")
test()

Output:
I learned Python Data Structures.
I am learning Decorators.

3.2.3 Generators
Sometimes, the number of elements in a set is large. If all the elements are read
and stored in the memory, there will be excessive hardware requirements. In this
case, you can use a generator to get the subsequent elements in a set through
loop.

In Python, a function that uses the yield keyword is called generator. A generator
can be used as follows:

● Create a generator using list derivation.


Use parentheses to write a generator.
G = (x*2 for x in range(5)) # Each x*2 in range(5)
print(type(G))
for i in G:
print (i)

Output:
<class 'generator'>
0
2
4
6
8

● Create a generator using yield.


Use the yield keyword to create a generator to generate the Fibonacci
sequence.
def fib(n):
current, num1, num2= 0, 0, 1 # Initialize numbers to start from 0, 1. Current means a loop.
while True:

2021-01-20 Huawei confidential. Page 36 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

if current > n: # The value is greater than the parameter value and
the loop ends.
return
yield num1 # yield turns the function into a generator, and the function is cyclically executed.
num1, num2 = num2, num1+num2
current += 1
fib(5)
for i in fib(5):
print (i)

Output:
0
1
1
2
3
5

● Wake up the generator.


The next and send methods can be used to wake up the generator. Different
from the next method, the send method can also transfer a piece of data to
the breakpoint when waking up the generator.
def gen():
i=0
while i<5:
temp = yield i
print(temp)
i+=1
f = gen()
next(f)
>>>0
f.send('haha')
>>>haha
>>>1
next(f)
>>>None
>>>2

3.2.4 Iterators
Iteration is a powerful function of Python and a way to access sets. An iterator is
an object that remembers the traversed positions. An iterator starts from the first
element for access until all elements are accessed.

An iterator has two basic methods: iter() and next(). The following is an example
of iterator:

● Determine objects that can be iterated.


An iterator supports only backward iterations. Strings, lists, and tuple objects
can be used to create iterators. The value cannot be iterated.
# Use the isinstance() method to determine whether an object can be iterated.
from collections import Iterable # Iterable object

2021-01-20 Huawei confidential. Page 37 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

print(isinstance([], Iterable))
print(isinstance('abc', Iterable))
print(isinstance({'a':1,'b':2},Iterable))
print(isinstance(100, Iterable))

Output:
True
True
True
False

● Basic methods of iterator


The iter() function is used to obtain the iterators of iterable objects. You can
use the next() function repeatedly for the obtained iterator to obtain the next
data record.
l = [1, 2, 3, 4, 5]
l_iter = iter(l)
next(l_iter)
>>>1
next(l_iter)
>>>2

● Class implementation iteration


An iterator implements the __iter__() and __next__() methods in a class.
The StopIteration exception identifies the completion of iteration and
prevents infinite loops.
class Count: # Declare a class implementation iterator.
def __iter__(self): # Implement the __iter__ method.
self.a = 1 # The initial value is 1.
return self
The def __next__(self): # Implement the __next__ method. The function can be +1.
if self.a <= 5:
x = self.a
self.a += 1
return x
else:
raise StopIteration # Iteration is complete.
mycount = Count()
myiter = iter(mycount)
for i in myiter: # Use the for loop to traverse the iterator.
print (i)

Output:
1
2
3
4
5

2021-01-20 Huawei confidential. Page 38 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

3.2.5 Multiple Tasks


Multi-task concurrent programming is a common function. Multi-task in Python
refers to multi-thread or multi-process.

A thread is a flow of instructions to complete a particular task, and is the smallest


executable unit that allocates time. A thread is usually located in a process and
consists of a program counter, a stack, a set of registers, and an identifier.
Common CPUs support multi-thread processing tasks.

A process contains a main thread and can generate multiple sub-threads. Each
thread contains its own registers and stacks. Processes can be single-thread or
multi-thread. Generally, an execution instance of a program is a process.

3.2.5.1 Multiple Threads


In Python, the threading module can be used to implement multiple threads.

● Use multiple threads to execute tasks.


import threading
from time import sleep,ctime # Use sleep to specify the program waiting time, and ctime to return the
local time.
def work1(): # Define the work1 function and output the work1 string at an interval of 1s.
for i in range(3):
print("work1 is being executed...%d"%i)
sleep(1)

def work2(): # Define the work2 function and output the work2 string at an interval of 1s.
for i in range(3):
print("work2 is being executed...%d"%i)
sleep(1)

if __name__ == '__main__':
print('---Start---:%s'%ctime())

t1 = threading.Thread(target=work1) # Thread 1 calls work1.


t2 = threading.Thread(target=work2 ) # Thread 2 calss work2.
# Start the thread.
t1.start()
t2.start()

sleep(5)
print('---End---:%s' %ctime())

Output:
---Start---:Mon Apr 15 10:55:16 2019
work1 is being executed...0
work2 is being executed...0
work1 is being executed...1
work2 is being executed...1
work1 is being executed...2
work2 is being executed...2
---End---:Mon Apr 15 10:55:21 2019

2021-01-20 Huawei confidential. Page 39 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

● Synchronize threads.
If multiple threads modify a piece of data at the same time, unexpected
results may occur. To ensure correct data, multiple threads need to be
synchronized. Lock can be used to implement simple thread synchronization.
This object has acquire and release methods. The concept of lock is
introduced to implement synchronization. A lock has two states: locked and
unlocked. Each time a thread, for example, wants to access shared data, it
must get the locked state. If another thread has gotten the locked state, the
thread is suspended. In this case, thread synchronization is blocked. Wait until
other threads finish their accesses and release the lock, and then continue
with the thread.
Example:
import threading
import time
g_num = 0 # Define a global variable and set its value to 0.
def test1(num): # Define the function test1 and perform the add operation to global variables.
global g_num # Use global variables.
for i in range(num):
mutex.acquire() # Lock
g_num += 1
mutex.release() # Unlock
print("---test1--- g_num=%d" %g_num)

def test2(num): # Define the function test2 and perform the add operation to global variables.
global g_num
for i in range(num):
mutex.acquire() # Lock
g_num += 1 # Perform the add operation.
mutex.release() # Unlock

print("---test2--- g_num=%d" %g_num)


# Create a mutual exclusion lock.
# By default, the global variables are not locked. You can delete the lock and view resource contention.
mutex = threading.Lock()

# Create two threads and add 1,000,000 times for g_num.


p1 = threading.Thread(target=test1, args=(1000000,))
p1.start()

p2 = threading.Thread(target=test2, args=(1000000,))
p2.start()

# Wait for the calculation to complete.


time.sleep(5)

print("After two threads operate the same global variable, the final result is: %s" % g_num)

Output:
---test1--- g_num=1868536
---test2--- g_num=2000000
After two threads operate the same global variable, the final result is: 2,000,000.

2021-01-20 Huawei confidential. Page 40 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

3.2.5.2 Multiple Processes


To perform multi-process operations in Python, the multiprocessing module is
required. The process class is similar to the multi-thread class.

# coding=gbk # Coding declaration


from multiprocessing import Process
import os
import time

nums = [11, 22] # Set global variables.

def work1():
"Code to be executed by subprocess 1. The nums list is extended."
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums)) # Get the process ID.
for i in range(3):
nums.append(i)
time.sleep(1)
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))

def work2():
"Code to be executed by subprocess 2. Process ID is output and list of nums is called.”
print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))

if __name__ == '__main__':
p1 = Process(target=work1)
p1.start()
p1.join() # After this thread is executed, execute other threads.

p2 = Process(target=work2)
p2.start()

Output:

D:\Python Learning>python test.py


in process1 pid=23384 ,nums=[11, 22]
in process1 pid=23384 ,nums=[11, 22, 0]
in process1 pid=23384 ,nums=[11, 22, 0, 1]
in process1 pid=23384 ,nums=[11, 22, 0, 1, 2]
in process2 pid=20588 ,nums=[11, 22]

Note: The Jupyter Notebook does not generate the result of this experiment
because of the editor. You can use Pycharm to execute code or create a .py file to
run it in CMD.

2021-01-20 Huawei confidential. Page 41 of 41

You might also like