Paepoi » Python Tips » Python POSIX
Python POSIX
最終更新日 2019.03.31
標準入出力
#!/usr/bin/env python3
# std
ss = input('Your Name?: ')
print('Herro {} san'.format(ss))
# sys 版、画面更新と改行に注意
import sys
sys.stdout.write('Your Name?: ')
sys.stdout.flush()
s = sys.stdin.readline().rstrip()
sys.stdout.write('Herro {} san\n'.format(s))
# 改行防止
print('aaa', end='')
# sep にて結合文字を変更、標準は半角スペース
print('aaa', 'bbb', sep=',') #=> aaa,bbb
# リダイレクト
with open('test.txt', 'w') as f:
print('てすと', file=f)
# {0} のエスケイプ
print('{{0}} {0}'.format('のエスケイプ'))
POSIX コマンド
#!/usr/bin/env python3
# posix という標準モジュールもありますが os と引数が同じ
# os モジュールがほぼすべてラップしているようです
import os
import subprocess
# ユーザーディレクトリ表示
# echo $HOME
print(os.getenv('HOME'))
# カレントディレクトリの取得
# pwd
print(os.getcwd())
# ディレクトリ作成
# mkdir __temp__
os.mkdir('__temp__')
# カレントディレクトリの移動
# cd __temp__
os.chdir('__temp__')
# リダイレクト
# echo まどか > from.txt
with open('from.txt', 'w') as f:
f.write('まどか')
# リダイレクト(追記)
# echo \nほむら >> from.txt
with open('from.txt', 'a') as f:
f.write('\nほむら')
# パーミッションの変更、8 進数に注意
# chmod 666 from.txt
os.chmod('from.txt', 0o666)
# シンボリックリンク作成
# ln -s from.txt link.txt
os.symlink('from.txt', 'link.txt')
# コマンドの実行
# cp from.txt to.txt
r = subprocess.run(['cp', 'from.txt', 'to.txt'])
if r.returncode != 0:
print('copy error')
# ファイルの読み込み
# cat to.txt
with open('to.txt') as f:
print(f.read())
# カレントディレクトリのファイル一覧
# ls
print(' '.join(os.listdir()))
# OS 情報、ホスト名
# uname -n
r = os.uname()
print(r.nodename)
# OS 情報、(Linux|Darwin)
# uname -s
print(r.sysname)
# 環境変数一覧
# env
for key in os.environ.keys():
print('{0}={1}'.format(key, os.getenv(key)))
端末入力とパイプ入力
#!/usr/bin/env python3
import sys, os
if os.isatty(0):
# 通常起動、stdin が開いている
print('コンソール')
else:
# stdin がパイプで既に使われている
# 行末に改行が含まれているので注意
print(sys.stdin.read().rstrip())
''' output
$ ./atty.py
コンソール
$ echo HOGE | ./atty.py
HOGE
'''
Ctrl+C で強制終了
#!/usr/bin/env python3 # This allows Ctrl+C to exit the program import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Linux 無限ループ (PyGPbject) from gi.repository import GLib loop = GLib.MainLoop() loop.run() # macOS 無限ループ (PyObjC) from AppKit import * NSApplication.sharedApplication() NSApp.run()
一行上に出力
#!/usr/bin/env python3
import sys, time
print('いくぞー')
for s in ['いーち', 'にー', 'さーん', 'だぁー!']:
time.sleep(1)
sys.stdout.write('\033[1A\033[0J') # 移動
print(s)
色分け表示
#!/usr/bin/env python3
# gnome-terminal, Terminal.app で確認
print('\033[32m緑色おおおお');
print('\033[31m赤色おおおお');
# 戻す
print('\033[39m', end='');
Copyright(C) sasakima-nao All rights reserved 2002 --- 2025.