Python: CygWin 環境におけるターミナル I/O 周りの調査
環境
- OS: Windows Server 2012 R2 日本語版
 - CygWin: 2.873 (64bit)
 - Python: 2.7
 
目的
Python 上で以下の操作が可能か調べる。
- ターミナルのエンコーディングの自動判別
 - ターミナル画面のクリア
 - ターミナル上のキー入力の検知
 
バリエーション
調査したバリエーションは以下 5 種類。
| 環境 | フロントエンド | シェル | Pythonビルド | エンコーディング | 
|---|---|---|---|---|
| 1 | cmd.exe | - | Windows | cp932 | 
| 2 | cmd.exe | CygWin bash | Windows | cp932 | 
| 3 | cmd.exe | CygWin bash | CygWin | UTF-8 | 
| 4 | MinTTY | CygWin bash | Windows | UTF-8 | 
| 5 | MinTTY | CygWin bash | CygWin | UTF-8 | 
環境情報
いくつかの方法で情報を取得。(要 import platform,os,sys,locale)
| # | メソッド | 環境1 | 環境2 | 環境3 | 環境4 | 環境5 | 
|---|---|---|---|---|---|---|
| a | platform.system() | Windows | Windows | CYGWIN_NT-6.3 | Windows | CYGWIN_NT-6.3 | 
| b | os.name | nt | nt | posix | nt | posix | 
| c | os.environ.get('TERM') | None | cygwin | cygwin | xterm | xterm | 
| d | os.environ.get('LANG') | None | ja_JP.UTF-8 | ja_JP.UTF-8 | ja_JP.UTF-8 | ja_JP.UTF-8 | 
| e | sys.stdin.isatty() | True | True | True | False | True | 
| f | sys.stdin.encoding | cp932 | cp932 | UTF-8 | None | UTF-8 | 
| g | sys.stdout.isatty() | True | True | True | False | True | 
| h | sys.stdout.encoding | cp932 | cp932 | UTF-8 | None | UTF-8 | 
| i | locale.getpreferredencoding() | cp932 | cp932 | UTF-8 | cp932 | UTF-8 | 
明快な判定方法は無いが、sys.stdout.encoding -> 環境変数LANG -> locale.getpreferredencoding() の順に信頼すれば良さそうに思える。
画面クリア
以下のメソッドの挙動を確認。(要 import subprocess)
| # | メソッド | 環境1 | 環境2 | 環境3 | 環境4 | 環境5 | 
|---|---|---|---|---|---|---|
| a | subprocess.call('cls', shell=True) | OK | OK | - | - | - | 
| b | subprocess.call('cmd /c cls', shell=True) | - | - | OK | - | - | 
| c | subprocess.call('clear', shell=False) | - | - | - | - | - | 
| d | subprocess.call(['echo', '-en', r'\ec'], shell=False) | - | - | OK | - | OK | 
| e | subprocess.call(r'echo -en "\ec"', shell=False) | - | OK | - | OK | - | 
なかなか判定条件が悩ましい。
キー入力の取得
msvcrt による取得が可能かどうかと、tty、curses が使えるかどうか調査。
| # | メソッド | 環境1 | 環境2 | 環境3 | 環境4 | 環境5 | 
|---|---|---|---|---|---|---|
| a | msvcrt.getch() | OK | OK | - | - | - | 
| b | tty.setraw(0) | - | - | OK | - | OK | b | curses.screen#getch() | - | - | OK | - | OK | 
環境4 に限っては、1文字単位でキー入力を取得する手段が無いという結論となった。
0 件のコメント:
コメントを投稿