2014-02-15

Python無名関数っぽいUnixコマンド作った。

GitHubとかブログやってないからここに書いておく。

使い方

標準入力を使いまわしたいとき

... | fun x:: cmd1 x : cmd2 x : ... : cmdn x | ...

ただしcmdにはサブシェルパイプなどは使用できない。

標準入力をそのまま利用する場合と一行毎に処理する場合

一行毎に処理する場合はxargs -Iを利用する。

$ ls *txt
a.txt b.txt
$ cat a.txt
1
$ cat b.txt
2
$ ls *txt | fun x:: echo x : cat x
a.txt b.txt
1
2
$ ls *txt | xargs -Ix fun _:: echo x : cat x
a.txt
1
b.txt
2

コード(fun)

>と<はそれぞれ大小の不等号で置き換えてくださいな

#!/usr/bin/env python
import sys
from subprocess import *

def take_variable(var):
	# check the syntax of variable (http://www.gnu.org/software/bash/manual/bash.html)
	# variable ::= (_|[A-z])(_|[A-z]|[0-9])*
	# variable contained space
	if len(var.split()) > 1:
		raise Exception('fail: the variable contained space')
	# check head
	if not (var[0].isalpha() or var[0] == '_'):
		raise Exception('fail: the variable contained wrong character')
	# check the body of variable
	b = True
	i = 0
	for c in var[1:]:
		i += 1
		# is variable contained invalid character?
		if not (c.isalpha() or c.isdigit() or c == '_'):
			b = False
			break
	# no exception if thre are only spaces after variable
	if not b and not var[i:].isspace():
		raise Exception('fail: the variable contained wrong character')
	elif b:
		return var[0]
	else:
		return var[:i]

def parse(var_to_cmds):
	# check the position of '::'
	try:
		pos = var_to_cmds.index('::')
	except Exception:
		raise Exception('not exists "::"')
	var = var_to_cmds[:pos]
	cmd_str = var_to_cmds[pos+2:]
	# check the format of variable and commands
	if var ==  '':
		raise Exception('fail: no variable before "::"')
	elif cmd_str == '':
		raise Exception('fail: no commands after "::"')

	return (take_variable(var),cmd_str)


if __name__ == '__main__':
	# parse variable and commands
	try:
		var,cmd_str = parse(' '.join(sys.argv[1:]))
	except Exception, e:
		print >>sys.stderr, e
		sys.exit(1)

	# var -> val
	val = sys.stdin.read().replace('\n',' ')
	# mapping and split by ':' again
	commands = map(
			(lambda cmd: cmd.replace(' '+var+' ',' '+val+' ')),
			cmd_str.split(':'))

	# exec command
	for cmd in commands:
		try:
			# need split for remove spaces
			check_call(cmd.split())
		except Exception,e:
			# print >>sys.stderr, e
			sys.exit(1)

本当はfunじゃなくて\(バックスラッシュ)で、:: じゃなくて→にしたかったんだけど、シェルが置き換えちゃうからしかたない

シェルの改造は禁断の手段だし

  • 増田でコードの色分けってどうやるんです?

    • 投稿時のボタン横に注目 http://hatenadiary.g.hatena.ne.jp/keyword/%E3%81%AF%E3%81%A6%E3%81%AA%E8%A8%98%E6%B3%95%E4%B8%80%E8%A6%A7 http://hatenadiary.g.hatena.ne.jp/keyword/%E3%82%BD%E3%83%BC%E3%82%B9%E3%82%B3%E3%83%BC%E3%83%89%E3%82%92%E8...

記事への反応(ブックマークコメント)

ログイン ユーザー登録
ようこそ ゲスト さん