Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

PythonのContext Managerの使い方

More than 5 years have passed since last update.

Context Managerとは

Pythonのwithブロックだけで行う処理を定義する際に利用する.

例:

withブロックなし

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

withブロックあり

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

実装例

paramikoパッケージを使って,withブロック内のみでサーバーに接続

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:
        # 前処理
        ssh = paramiko.SSHClient()
        ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        ssh.connect(host, username=username, password=password)
        yield ssh  # asで受け取りたい変数
    finally:
        # 後処理
        ssh.close()
with connect_ssh('server', 'username') as f:
    _, stdout, stderr = f.exec_command('ls')
    print(stdout.read())
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away