How to use Python's Context Manager

What is Context Manager?

It is used when defining the processing to be performed only by the with block of Python.

Example:

with no block

f = open('hoge.txt', 'w')
f.write('hoge\n')
f.close()

There is a with block

with open('hoge.txt', 'w') as f:
    f.write('hoge\n')

Implementation example

Connect to the server only within the with block using the paramiko package

import os
from contextlib import contextmanager

import paramiko


def connect_ssh(host, username=None, password=None):
    return _connect_ssh_context(host, username, password)


@contextmanager
def _connect_ssh_context(host, username, password):
    try:
        #Preprocessing
        ssh = paramiko.SSHClient()
        ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        ssh.connect(host, username=username, password=password)
        yield ssh  #Variables you want to receive with as
    finally:
        #Post-processing
        ssh.close()
with connect_ssh('server', 'username') as f:
    _, stdout, stderr = f.exec_command('ls')
    print(stdout.read())

Recommended Posts

How to use Python's Context Manager
How to use Python's logging module
How to use Nix package manager
How to use TouchDesigner Python's external module
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes
How to use cron (personal memo)
Python: How to use async with