#!bin/python3
#coding:utf-8

# Copyright (C) 2019 Momi-g
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

def sh(pin, cmd):	#pin...bynary. 一括read(),メモリ注意。大出力は >tmp.txt 推奨。
	import subprocess as sb
	if len(pin) != 0:
		pr=sb.Popen(["sh","-c",cmd], stdin=sb.PIPE, stdout=sb.PIPE)
		pr.stdin.write(pin)
		pr.stdin.close()	# send EOF
	else:
		pr=sb.Popen(["sh","-c",cmd], stdout=sb.PIPE)
	brtn=pr.stdout.read()
	pr.stdout.close()
	return brtn


def usage():	
	msg=r"""HowTo (sh_bind.py, python <-> sh pipe work helper)
------
eg)	#!/bin/python3
	def sh(pin, ...
		...
		return brtn		# copy&paste func sh()

	inn=b'1 2 3 2'
	cmd=rb''' tr " " '\n' | sort -nr | uniq '''
	out=sh(inn, cmd)    
	print(out.decode() )	#>> 3,2,1

 # eq code: ~$ echo "1 2 3 2" | tr " " '\n' | sort -nr | uniq
 # input/output is binary.
	
	cmd=rb''' ls -l '''
	out=sh(b'', cmd)    
	print(out.decode() )	#>> show filenames
	
 # eq code: ~$ ls -l
 # if len(inn) == 0, skip pipe input."""
	print(msg)


import sys
if __name__ == "__main__":
#	bin in, bin out.
	if len(sys.argv) != 1:
		usage()
		exit()
	
	print("usage: ...see -h.")
	print()
	
	inn=b'1 2 3 2'
	cmd=rb''' tr " " '\n' | sort -nr | uniq '''
	out=sh(inn, cmd)    
	print(out )	#>> 3,2,1
	print()

	cmd=rb''' ls -l | head -n 5 ; echo "...show only 5 lines."'''
	out=sh(b'', cmd)    
	print(out.decode() )	#>> show filenames
