diff -ur v2/chat_conn.py v3/chat_conn.py --- v2/chat_conn.py 2019-08-11 23:59:01.000000000 +0900 +++ v3/chat_conn.py 2019-08-13 12:57:29.000000000 +0900 @@ -5,6 +5,11 @@ import select import time import threading +import subprocess +try: + import queue +except: + import Queue as queue tmout = 3.0 @@ -377,18 +382,18 @@ return e.to_attr( locals() ) -def cli(host, port, name0): +def client(host, port, name0, func_in, func_out): cli = cli_new(host, port, name0) th_quit = threading.Event() def th_func(): rest = rest_new() while not th_quit.wait(0): - if not readable(sys.stdin): - continue - s = sys.stdin.readline() - if not s: + s = func_in() + if s == False: break + if not s: + continue cli.send_to('', s) th = threading.Thread( target=th_func ) @@ -404,15 +409,40 @@ (f, s) = r if f: s = '{}> {}'.format(f, s) - print(s) + func_out(s) th_quit.set() th.join() cli.dis_conn() +def cmd_io_new(cmd): + que = queue.Queue() + + def func_in(): + s = None + if cmd: + try: + s = que.get(timeout=tmout) + except: + s = None + elif readable(sys.stdin): + s = sys.stdin.readline().strip() + return s + + def func_out(s): + if cmd: + echo_cmd = 'echo "{}" | {}'.format(s, cmd) + ret = subprocess.check_output(echo_cmd, shell=True).decode('utf-8').strip() + if ret: + que.put(ret) + else: + print(s) + + return Empty( locals() ) + def help(v): ss = [ - 'Usage: {} [conn [] []]'.format(sys.argv[0]), + 'Usage: {} [conn [] [host=] [cmd=]]'.format(sys.argv[0]), ' conn: client mode', ' user name: default "guest"', ' hostname: default "localhost"', @@ -421,21 +451,27 @@ sys.exit(v) if __name__ == "__main__": - arg = lambda i, def_v=None: sys.argv[i] if sys.argv[i:] else def_v + av = sys.argv[1:] + pop = lambda def_v=None: av.pop(0) if av else def_v + def pop_k(k, def_v=None): + for i in range( len(av) ): + if av[i].startswith(k): + return av.pop(i)[ len(k): ] + return def_v - port = int( arg(1, '-1') ) + port = int( pop('-1') ) if port < 0: help(1) - - kind = arg(2) + kind = pop() if not kind: srv(port) sys.exit(0) if kind != 'conn': - help(2) - - name0 = arg(3, 'guest') - host = arg(4, 'localhost') + help(2) + host = pop_k('host=', 'localhost') + cmd = pop_k('cmd=', '') + name0 = pop('guest') + cmd_io = cmd_io_new(cmd) - cli(host, port, name0) + client(host, port, name0, cmd_io.func_in, cmd_io.func_out) # EOF