LoginSignup
0
2

More than 3 years have passed since last update.

pythonでLinuxコマンド文字列を整形する汎用的なプログラム

Last updated at Posted at 2019-11-03

背景

Linuxコマンドを用いて例えばCPU温度などを定期的にDBに追加しています。
この時にコードをなるべく少なくしようとコマンドだけで色々と調べたのですがなかなか難易度が高かったので作成しました。

仕様

汎用的に利用できるようにしたいのでpythonのFormatのような動きを実現させたい。

コード

こうなりました。

import sys;
print(sys.argv[1].format(*sys.argv[2].split(" ")) )
  • 第一引数:Formatの指定文字列
  • 第二引数:空白で区切られたFormatに入れる文字列

利用方法

mosquitto_sub -t "#" -v |xargs -I@ python3 /home/hashito/command/text2format.py "insert into mqtt.msg (t,m,tm)values(\'{}\',\'{}\',UNIX_TIMESTAMP(NOW()))" @ | xargs -I@ mysql -e "@"

mqttの内容を雑にマリアDBにつっこめます

追記

@shiracamus 様からコメントいただきました。
コマンドのみだと下記の形で出来るようです。

$ echo "a b" | xargs echo | xargs printf "insert into mqtt.msg (t,m,tm)values('%s','%s',UNIX_TIMESTAMP(NOW()))"
insert into mqtt.msg (t,m,tm)values('a','b',UNIX_TIMESTAMP(NOW()))

これをずっと探していたのですが、自分の知識がなく助かりました!
ありがとうございました!

0
2
4

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
0
2