各サンプルコード

以下に、それぞれのサンプルコードの例を示します。

  1. データベース接続:
python
import sqlite3 # データベース接続のコンテキストマネージャ with sqlite3.connect('example.db') as conn: cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)') cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
  1. ロックの管理:
python
import threading import time # ロックのコンテキストマネージャ lock = threading.Lock() def worker(): with lock: print('Locked, doing some work...') time.sleep(2) print('Work done, releasing lock') thread1 = threading.Thread(target=worker) thread2 = threading.Thread(target=worker) thread1.start() thread2.start()
  1. ネットワーク接続:
python
import socket # ソケットのコンテキストマネージャ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(('example.com', 80)) s.sendall(b'GET / HTTP/1.1rnHost: example.comrnrn') response = s.recv(1024) print(response.decode())
  1. ファイルシステム操作以外のファイル操作:
python
import os # ファイル属性の変更 with open('example.txt', 'w') as f: f.write('Hello, world!') # ファイルのロック with open('example.txt', 'r') as f: fcntl.flock(f.fileno(), fcntl.LOCK_EX) data = f.read() print(data) fcntl.flock(f.fileno(), fcntl.LOCK_UN)

これらのコード例では、それぞれのリソース(データベース、ロック、ソケット、ファイル)をwith構文を使って管理しています。withブロックを抜ける際には、それぞれのリソースが確実に解放されます。

未分類

Posted by ぼっち