LoginSignup
14
15

More than 5 years have passed since last update.

PythonのContext Managerの使い方

Last updated at Posted at 2015-10-04

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())
14
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15