56

Coding 1002 - Getting · Helpful Interactive Python Commands •dir() • Return all variable, classes, objects (collectively called “names”)available •dir(name) • Return

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Shweta Palande, DevNet Developer Advocate

DEVNET-1893.c

Coding 1002 - Getting Started with Python

Questions? Use Cisco Webex Teams to chat with the speaker after the session

Find this session in the Cisco Events Mobile App

Click “Join the Discussion”

Install Webex Teams or go directly to the team space

Enter messages/questions in the team space

How

1

2

3

4

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Cisco Webex Teams

DEVNET-1893.c 3

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Agenda

• Why Python and How to get it?

• Breaking Down Python Code

• Interacting with Python Live

• What are Libraries and How to Use Them

• Using pip to Install Libraries

• Virtual Environments

• Foundational Libraries4

DEVNET-1893.c 4

Why Python and How to get it?

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

http://www.python.org/about

Python is powerful... and fast;plays well with others;runs everywhere;is friendly & easy to learn;is Open.

DEVNET-1893.c 6

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Why Python for Network Engineers

• Readable and easy to learn

• Widely available and Open Source

• Windows, Mac, Linux

• Routers & Switches

• Many relevant code samples

• Lots of training resources

DEVNET-1893.c 7

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

How to get Python?

• You might already have it

• http://python.org/downloads

• Package Management Tools

• Example: Homebrew for Mac

• brew install python2

• brew install python3

DevNet$ python –version

Python 2.7.12

DevNet$ python

Python 2.7.12 (default, Oct 11 2016,

05:20:59)

[GCC 4.2.1 Compatible Apple LLVM 8.0.0

(clang-800.0.38)] on darwin

Type "help", "copyright", "credits" or

"license" for more information.

>>>

DEVNET-1893.c 8

Let’s cover some basics

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Math Operations

Addition: +

Subtraction: -

Multiplication: *

Division: /

Floor Division: / /

Modulo: %

Power: * *

Numerical Operators

10

>>> 5 + 2

7

>>> 9 * 12

108

>>> 13 / 43.25

>>> 13 // 4

3

>>> 13 % 4

1

>>> 2 ** 10

1024

DEVNET-1893.c

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Names

• Cannot start with a number [0-9]

• Cannot conflict with a language

keyword

• Can contain: [A-Za-z0-9_-]

• Recommendations for naming (variables, classes, functions, etc.) can be found in PEP8

Created with the = assignmentoperator

Can see list of variables in thecurrent scope with dir()

Variables

11DEVNET-1893.c

>>> b = 7

>>> c = 3

>>> a = b + c

>>> a

10

= "Foo"

= "Bar"

= string_one + string_two

>>> string_one

>>> string_two

>>> new_string

>>> new_string

'FooBar'

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Conditionals

12

• Syntax:

• i f expression1 :

• sta t ements …

• e l i f expression2 :

• statements…

• e l s e :

• statements…

✓ Indentation is important!

✓ 4 spaces indent recommended

✓ You can nest if statements

<

>

Comparison Operators:

Less than

Greater than

Less than or equal to

Greater than or equal to

Equal

Not Equal

Contains element

<=

>=

==

!=

i n

Combine expressions with: and, or

Negate with: not

DEVNET-1893.c

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

is less than zero")

is exactly zero")

is greater than zero")

is something else")

Conditionals | Examples

13

>>> b = 5

>>> if b < 0:

... print("b

... elif b == 0:

... print("b

... elif b > 0:

... print("b

... else:

... print("b

...b is greater than zero

>>> words = "Foo Bar"

>>> if "Bar" in words:

... print("words contains 'Bar'")

... elif "Foo” in words:

... print("words contains 'Foo'")

...

words contains 'Bar'

DEVNET-1893.c

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Modularize your code

• Defining your own Functions

• (optionally) Receive arguments

• (optionally) Return a value

Syntax:

def function_name(arg_names):

statements…

return value

...

function_name(arg_values)

Functions | Don’t Repeat Yourself

14

num2

add(3, 5)

>>> def add(num1, num2):

... result = num1 +

... return result

...

>>>

>>>

8

>>> def say_hello():

... print("Hello!")

>>>

>>> say_hello()

Hello!

DEVNET-1893.c

Python Collections and Loops

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Data Structures / Collection Data Types

16

Namet y p e ( )

Notes Example

l i s t • Ordered list of items

• Items can be different data types

• Can contain duplicate items

• Mutable (can be changed after created)

[ ‘a ’ , 1 , 18.2]

tuple • Just like a list; except:

• Immutable (cannot be changed)

( ‘a ’ , 1 , 18.2)

dictionaryd i c t

• Unordered key-value pairs

• Keys are unique; must be immutable

• Keys don’t have to be the same data type

• Values may be any data type

{“apples”: 5 ,

“pears”: 2 ,

“oranges”: 9}

DEVNET-1893.c

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Some useful dictionary methods:

{ } . i tems( )

{ } .keys( )

{ } .va lues( )

There are many more! 😎

Dictionary Methods

17

>>> d = {"a": 1, "b": 2, "c": 3}

>>> d . i t e m s ( )

d i c t _ i t e m s ( [ ( ' a ’ , 1 ) , ( ' b ’ , 2 ) , ( ' c ' , 3 ) ] )

>>> d . k e y s ( )

dict_keys([ 'a’, ' b ’ , ' c ’ ] )

>>> d . v a l u e s ( )

dict_values([1, 2 , 3] )

DEVNET-1893.c

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Conditional Loops

while l og ica l_express ion :

statements…

Loops

18

Iterative Loops

f or i n d i v i d u a l _ i tem i n

i t e r a t o r :

statements…

>>> i = 0

>>> while True:

... print(i)

... i += 1

...

0

1

2

3

4

>>> names = ["chris", "iftach", "jay"]

>>> for name in names:

... print(name)

...

chris

iftach

jay

DEVNET-1893.c

Breaking Down Python Code

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

example1.py

• Script Structure and Format

• Importing and using packages

• Variable declaration and usage

• Function creations and usage

• Basic Error Handling

DEVNET-1893.c 20

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

example1.py

• Script Structure and Format

• Importing and using packages

• Variable declaration and usage

• Function creations and usage

• Basic Error Handling

DEVNET-1893.c 21

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

example1.py

• Script Structure and Format

• Importing and using packages

• Variable declaration and usage

• Function creations and usage

• Basic Error Handling

DEVNET-1893.c 22

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

DevNet$ python example1.py

You must provide a number as a parameter to this script

Example:

python example1.py 12

DevNet$ python example1.py 5

10.0

DevNet$ python example1.py 45.4

90.8

netprog_basics/programming_fundamentals/python_part_1/example1.py

example1.py – Testing the Code

DEVNET-1893.c 23

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public

example2.py

• Reading from and writing to files

• The “with” statement

• Requesting interactive user input

• Writing to the command line

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

example2.py

• Reading from and writing to files

• The “with” statement

• Requesting interactive user input

• Writing to the command line

DEVNET-1893.c 25

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

example2.py

• Reading from and writing to files

• The “with” statement

• Requesting interactive user input

• Writing to the command line

DEVNET-1893.c 26

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public

DevNet$ python example2.py

What is your name? Hank

Adding new log entry

Log File Contents

-----------------

Entry logged at: 2017-07-25 23:11:16.168003 by Hank

Entry logged at: 2017-07-26 00:17:03.199335 by Hank

example2.py – Testing the Code

netprog_basics/programming_fundamentals/python_part_1/example2.py

netprog_basics/programming_fundamentals/python_part_1/example2.log

Interacting with Python Live

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

What is and Why use Interactive Python

• Real-time enter code and see results

• Experiment and learning

• Debug scripts that aren’t working

• Build on the output of a script

DEVNET-1893.c 29

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Accessing Interactive Python

• python –i

• Basic command line

• python –i script.py

• Run a script and leave session active

• idle

• Basic interpreter client written in Python

• Virtual Environmentpython –m idlelib.idle

DevNet$ python -i

Python 3.6.2 (default, Jul 17 2017, 16:44:45)

[GCC 4.2.1 Compatible Apple LLVM 8.1.0

(clang-802.0.42)] on darwin

Type "help", "copyright", "credits" or

"license" for more information.

>>> from pprint import pprint

>>> pprint("Hello World")

'Hello World'

>>> exit()

DevNet$ python -i example1.py 21

42.0

>>> doubler(3)

6

>>> exit()

DevNet$ idle

DEVNET-1893.c 30

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Helpful Interactive Python Commands

• dir()

• Return all variable, classes, objects(collectively called “names”) available

• dir(name)

• Return attributes for an object

• help(name)

• Built-in help system. Displays docs and info for object

DEVNET-1893.c 31

Demo

What are Libraries and How to Use Them

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Python Libraries (Modules, Applications, etc)

• Any Python code outside of your script you want to use

• Provide some capability or data you need

• Included with statements• from library import name

• import library

DEVNET-1893.c 34

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Python Libraries (Modules, Applications, etc)

• Any Python code outside of your script you want to use

• Provide some capability or data you need

• Included with statements• from library import name

• import library

DEVNET-1893.c 35

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Where to get Libraries

• Write them yourself• Example: common_vars

• Included with Python itself• Example: datetime, os, sys, json

• From Python Package Index (PyPI)• Example: pip install requests

• Download and install manually• Example: ACI Toolkit from GitHub

netprog_basics/programming_fundamentals/python_part_2/common_vars.py

Using pip to Install Libraries

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Pip, The Python Package Installer

• Python 2.7.6 and Python 3.4 or greater includes by default

• Integrates with PyPI for packages

• Install, Upgrade, and Uninstall packages

• “requirements.txt” in projects provide input to pip

DevNet$ pip --version

pip 9.0.1

DevNet$ pip install pyang

Collecting pyang

Downloading pyang-1.7.3-py2.py3-none-any.whl

(326kB)

100% |████████████████████████████████| 327kB

1.3MB/s

Installing collected packages: pyang

Successfully installed pyang-1.7.3

DevNet$ pip install -r requirements.txt

Collecting requests (from -r requirements.txt (line

1))

Downloading requests-2.18.2-py2.py3-none-any.whl

(88kB)

100% |████████████████████████████████| 92kB

662kB/s

.

{OUTPUT TRUNCATED}

.

Successfully installed requests-2.18.2 six-1.10.0

urllib3-1.22

netprog_basics/programming_fundamentals/python_part_2/requirements.txt

DEVNET-1893.c 38

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

pip Commands to Know

• Install a package• pip install package

• Upgrade a package• pip install --upgrade package

• Uninstall a package• pip uninstall package

• View all packages installed• pip freeze

• Install “requirements.txt”• pip install –r requirements.txt

DevNet$ pip freeze

asn1crypto==0.22.0

bcrypt==3.1.3

certifi==2017.4.17

cffi==1.10.0

chardet==3.0.4

cryptography==2.0

flake8==3.3.0

idna==2.5

lxml==3.8.0

mccabe==0.6.1

ncclient==0.5.3

paramiko==2.2.1

pyang==1.7.3

pyasn1==0.2.3

pycodestyle==2.3.1

pycparser==2.18

pyflakes==1.5.0

PyNaCl==1.1.2

requests==2.18.2

six==1.10.0

urllib3==1.22

DEVNET-1893.c 39

Virtual Environments

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

What is a Virtual Environment (venv)

• Build isolated, fully functional Python environments on a single workstation

• Virtual Environments can• Run different versions of Python

• Have different libraries installed

• Have different versions of libraries installed

DEVNET-1893.c 41

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Setting Up a Virtual Environment

DevNet$ pip install virtualenv

Successfully installed virtualenv

DevNet$ virtualenv venv

New python executable in

/private/tmp/venv/bin/python2.7

Also creating executable in

/private/tmp/venv/bin/python

Installing setuptools, pip, wheel...done.

DevNet$ virtualenv venv2 --python=python3

Running virtualenv with interpreter

/usr/local/bin/python3

Using base prefix

'/usr/local/Cellar/python3/3.6.2/Frameworks/Python.fr

amework/Versions/3.6'

New python executable in

/private/tmp/venv2/bin/python3.6

Also creating executable in

/private/tmp/venv2/bin/python

Installing setuptools, pip, wheel...done.

DevNet$ source venv/bin/activate

(venv) DevNet$

* Commands on Windows Platforms slightly different

• Install the virtualenv library• pip install virtualenv

• Create the Virtual Environment• virtualenv name

• Specify Python Version• virtualenv name --python=python3

• Activate Virtual Environment• source name/bin/activate*

• Deactivate Virtual Environment• deactivate

DEVNET-1893.c 42

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Installing Python Libraries in Virtual Environments

• Once activated, no different(venv) DevNet$ pip install pyang

Collecting pyang

Downloading pyang-1.7.3-py2.py3-none-any.whl

(326kB)

100% |████████████████████████████████| 327kB

1.3MB/s

Installing collected packages: pyang

Successfully installed pyang-1.7.3

(venv) DevNet$ pip install -r requirements.txt

Collecting requests (from -r requirements.txt (line

1))

Downloading requests-2.18.2-py2.py3-none-any.whl

(88kB)

100% |████████████████████████████████| 92kB

662kB/s

.

{OUTPUT TRUNCATED}

.

Successfully installed requests-2.18.2 six-1.10.0

urllib3-1.22

DEVNET-1893.c 43

Foundational Libraries

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Core Python Libraries to Know and Love

• Pretty Print• from pprint import pprint

• Python Interpreter Utilities• import sys

• Operating System Interfaces• import os

• Date and Time Utilities• import datetime

* Many libraries included with core Python, see docs

DEVNET-1893.c 45

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Prettier Printing with pprint

• Better formatting than default print() function

https://docs.python.org/3/library/pprint.html

DEVNET-1893.c 46

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Access Details about Python with sys

• Access to some details/variables concerning running state• Access command line arguments withsys.argv[]

• Access to functions that interact withthe interpreter

• Exit Python with specific error messagesys.exit("Message")

DevNet$ python -i common_vars.py "CLI Arg 1" "CLI Arg 2"

>>>

>>> import sys

>>>

>>> sys.argv[1]

'CLI Arg 1'

>>> sys.argv[2]

'CLI Arg 2'

>>>

>>> sys.exit("Error Occurred")

Error Occurred

https://docs.python.org/3/library/sys.html

DEVNET-1893.c 47

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Interact with Files, Paths, and Environment with os

• Access and manipulate directories and files• Note: Opening files can be done withopen(filename)

• Access and Manipulate EnvironmentVariables• os.environ[var_name]

https://docs.python.org/3/library/os.html

DEVNET-1893.c 48

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Get your Date and Time Correct with datetime

• Create, format, and manipulate dates and times

• Time arithmetic!

• Work with timestamps and other representations

https://docs.python.org/3/library/datetime.html

DEVNET-1893.c 49

Demo

Summing up

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Review

• Why Python and How to get it?

• Breaking Down Python Code

• Script structure, imports, variables, functions & errorhandling

• Working with files and command line input

• Using lists and dictionaries, loops, and conditional statements

• Interacting with Python Live

• How to access the Python interpreter

• Using dir() and help() to explore and learn

• Understand what Python libraries are and how to use them

• Looked at Python Virtual Environments, why and how to use them

• Explored core Python libraries for displaying data, managing running scripts, and workingwith the operating system

DEVNET-1893.c 52

Complete your online session survey • Please complete your session survey

after each session. Your feedback is very important.

• Complete a minimum of 4 session surveys and the Overall Conference survey (starting on Thursday) to receive your Cisco Live t-shirt.

• All surveys can be taken in the Cisco Events Mobile App or by logging in to the Content Catalog on ciscolive.com/emea.

Cisco Live sessions will be available for viewing on demand after the event at ciscolive.com.

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco PublicDEVNET-1893.c 53

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public

Related sessions

Walk-In LabsDemos in the Cisco Showcase

Meet the Engineer 1:1 meetings

Continue your education

54DEVNET-1893.c

Thank youThank you