ログ監視 Python watchdog(ログローテーション未完成)

アプリケーションのログファイルを監視するシステムをつくる。 ファイルの更新をきっかけにコマンド実行 (python編) - Qiita ログ監視スクリプト - Qiita 上の2つをがっちゃんこしたやつを作った。ファイルの変更監視はwatchdog、読み取りはふつうのIO。 ※ うーん、ログローテーション対応が微妙かも from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import time import os from stat import * class FileWatchHandler(FileSystemEventHandler): def __init__(self, path): self.path = os.path.realpath(path) self.fp = None self.fpos = None self.init() filesize = os.stat(self.path)[ST_SIZE] self.fp.seek(filesize) # ファイル末尾 self.fpos = filesize def init(self): fp = self.fp if fp: fp.close() fp = open(self.path, 'r') self.fp = fp self.fpos = None def on_created(self, event): if event.src_path == self.path: print('reset') self.init() def on_modified(self, event): if event.src_path == self.path: print('modified') self.tail_f() def tail_f(self): if self.fpos: self.fp.seek(self.fpos) while True: self.fpos = self.fp.tell() line = self.fp.readline() if not line: break self.analyze(line) def analyze(self, line): # TODO: print('!', line) def close(self): self.fp.close() path = 'test.txt' handler = FileWatchHandler(path) observer = Observer() observer.schedule(handler, os.path.dirname(os.path.realpath(path))) observer.start() try: observer.join() except KeyboardInterrupt: pass observer.stop() handler.close() print('closed') ※ ちょっと修正してみたけど、やっぱり微妙 ...

2019年7月10日 · aoirint

Open JTalk mpg123

Open JTalkの出力したwavをmpg123で再生したらエラー出た。 [src/libmpg123/layer1.c:30] error: Illegal bit allocation value. [src/libmpg123/layer1.c:171] error: Aborting layer I decoding after step one. ffmpegでmp3に変換して再生するとok。mpg123では同じくエラーで変換できなかった。 ffmpeg -i b.wav b.mp3 mpg123 b.mp3 ffmpegのinfo Guessed Channel Layout for Input Stream #0.0 : mono Input #0, wav, from 'b.wav': Duration: 00:00:01.17, bitrate: 768 kb/s Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 48000 Hz, mono, s16, 768 kb/s Input #0, mp3, from 'b.mp3': Metadata: encoder : Lavf57.56.101 Duration: 00:00:01.20, start: 0.023021, bitrate: 65 kb/s Stream #0:0: Audio: mp3, 48000 Hz, mono, s16p, 64 kb/s ffmpeg -i b.wav c.wav これもダメ ...

2019年5月25日 · aoirint

Open JTalk

# Open JTalk Test # python3 # exec `apt install open-jtalk open-jtalk-mecab-naist-jdic` # get `mei_normal.htsvoice` from http://www.mmdagent.jp/ import subprocess p = subprocess.Popen('open_jtalk -x /var/lib/mecab/dic/open-jtalk/naist-jdic -m mei/mei_normal.htsvoice -r 1.0 -ow /dev/stdout', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) text = 'こんにちは' out, err = p.communicate(text.encode('utf-8')) print(text) print(err) # outにwavのバイナリが入ってる。必要に応じてここ変えてね with open('b.wav', 'wb') as fp: fp.write(out) subprocess で shell=True でリストを与えたときの挙動 - Qiita 合成音声(Open Jtalk)でwavファイルを作成しないで再生する - Qiita python - input directly in process.communicate() in subprocess library - Stack Overflow subprocessについて調べたメモ - Qiita Debian Jessie に OpenJtalk を入れてテキストを読み上げてみた - 残しときます(自分用) 日本語音声合成Open JTalkをPythonから実行する - 動かざることバグの如し mmdagent.jp Open JTalk - HMM-based Text-to-Speech System See also mpg123

2019年5月25日 · aoirint

json, bson, sqlite3 IOの実験メモ

Windows 10 Python 3.6.6 bson==0.5.7 SSD JSON import json import random import time file = 'test.tmp' N = 500 # Generate start = time.time() entries = [] for i in range(N): title = ''.join([ chr(random.randint(ord('あ'), ord('ん')+1)) for i in range(32) ]) body = ''.join([ chr(random.randint(ord('あ'), ord('ん')+1)) for i in range(30000) ]) entries.append({ 'id': i, 'title': title, 'body': body, }) data = { 'entries': entries, } end = time.time() print('Generate: %.1fs' % (end - start, )) Generate: 38.6s import os # Write start = time.time() with open(file, 'w', encoding='utf-8') as fp: json.dump(data, fp, ensure_ascii=False) end = time.time() print('Write: %.3fs' % (end - start, )) print('%.2fMB' % (os.path.getsize(file)/(1024**2), )) # Read start = time.time() with open(file, 'r', encoding='utf-8') as fp: data = json.load(fp) end = time.time() print('Read: %.3fs' % (end - start, )) Write: 0.252s 42.98MB Read: 0.214s BSON pip install bson import bson # Write start = time.time() s = bson.dumps(data) print('%.2fMB' % (len(s)/(1024**2), )) dumpEnd = time.time() with open(file, 'wb') as fp: fp.write(s) end = time.time() print('Write: %.3fs (Dump: %.3fs)' % (end - start, dumpEnd - start)) # Read start = time.time() with open(file, 'rb') as fp: s = fp.read() loadStart = time.time() data = bson.loads(s) end = time.time() print('Read: %.3fs (Load: %.3fs)' % (end - start, end - loadStart)) 42.98MB Write: 0.830s (Dump: 0.638s) Read: 0.156s (Load: 0.095s) SQLite3 import sqlite3 if os.path.exists(file): os.unlink(file) start = time.time() with sqlite3.connect(file) as db: cur = db.cursor() cur.execute( 'CREATE TABLE entries(id INTEGER AUTO INCREMENT, title TEXT, body TEXT)' ) for entry in data['entries']: cur.execute( 'INSERT INTO entries VALUES(?,?,?)', ( entry['id'], entry['title'], entry['body'], ), ) end = time.time() print('Write: %.3fs' % (end - start, )) start = time.time() with sqlite3.connect(file) as db: cur = db.cursor() results = [] for row in cur.execute('SELECT * FROM entries'): results.append(row) end = time.time() print('Read: %.3fs' % (end - start, )) print('%.2fMB' % (os.path.getsize(file)/(1024**2), )) db.close() Write: 1.093s Read: 0.243s 43.22MB

2018年12月15日 · aoirint

HOG特徴量の計算(Scikit-image)

pip install scikit-image from skimage.feature import hog import numpy as np size = 32 channel = 1 image = np.random.randn(size, size, channel) feature = hog(image) print(feature.shape) print(feature) デフォルト(勾配方向数9, セルサイズ8, ブロックサイズ3)では32x32の画像に対して324次元のHOG特徴量が出力される。 出力例 (324,) [0.01877925 0.00125122 0.00899619 0.00630656 0.01330613 0.0150924 ... 0.00763393 0.01668535 0.01852621 0.01204107 0.00433798 0.01147866] 画像からHOG特徴量の抽出 - Qiita https://web.archive.org/web/20170917002713/http://qiita.com/mikaji/items/3e3f85e93d894b4645f7 ドキュメント: https://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.hog

2018年12月15日 · aoirint

PythonからPaSoRiを使って交通系ICカードのIDmを読む

環境 Ubuntu 18.04 (VirtualBox on Windows 10) Python 2.7.15rc1(nfcpyはPython3非対応のため) Sony PaSoRi RC-S380 Suica (2019/12/19 追記)未検証ですがnfcpyがv1.0.0でPython3対応したみたいです。https://github.com/nfcpy/nfcpy/issues/47#issuecomment-499693493 セットアップ まずPaSoRiを接続する。PaSoRiをUSBポートに挿して、VirtualBox仮想マシンの設定からUSB、USB デバイスフィルターにSONY RC-S380/Pを追加。 $ lsusb Bus 001 Device 004: ID 054c:06c3 Sony Corp. ... これでOK。 次にnfcpyのインストール(※Python2に導入すること、virtualenvを使うといいのでは)。 pip install nfcpy いくらか準備が必要なので、python -m nfcを実行する。 $ python -m nfc No handlers could be found for logger "nfc.llcp.sec" This is the 0.13.5 version of nfcpy run in Python 2.7.15rc1 on Linux-4.15.0-33-generic-x86_64-with-Ubuntu-18.04-bionic I'm now searching your system for contactless devices ** found usb:054c:06c3 at usb:001:004 but access is denied -- the device is owned by 'root' but you are 'USERNAME' -- also members of the 'root' group would be permitted -- you could use 'sudo' but this is not recommended -- better assign the device to the 'plugdev' group sudo sh -c 'echo SUBSYSTEM==\"usb\", ACTION==\"add\", ATTRS{idVendor}==\"054c\", ATTRS{idProduct}==\"06c3\", GROUP=\"plugdev\" >> /etc/udev/rules.d/nfcdev.rules' sudo udevadm control -R # then re-attach device I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break other serial devs Sorry, but I couldn't find any contactless device 一般ユーザーの場合こんなメッセージが出るので、指示通りデバイスをplugdevグループに割り当てる。 ...

2018年8月30日 · aoirint

MSYS2でPython3を使う

What MSYS2でPython3を使いたい。 Environment Windows 10 Home How $ pacman -S pythonで最新のPythonが入る。 $ pacman -S python3-pipでPython3のpipが入る。 例えばPython 3.6.2を入れたとして、実行するにはpython、python3かpython3.6。 Appendix バージョン合わせ export PATH="/mingw64/bin:${PATH}" 上のように.bash_profileをいじってMinGWのbinをPATHに入れて動かしていると、pythonのバージョンが合わないときがある。 pythonで最新のPythonを動かしたいときは、 export PATH="${PATH}:/mingw64/bin" とすれば動く。

2017年9月24日 · aoirint