Skip to content

Instantly share code, notes, and snippets.

@loplex
Created April 14, 2019 08:45
Show Gist options
  • Save loplex/017baaeb1481650dc828f93b14d05477 to your computer and use it in GitHub Desktop.
Save loplex/017baaeb1481650dc828f93b14d05477 to your computer and use it in GitHub Desktop.
allows to send data to STDIN of another process already running having STDIN attached to terminal
#!/usr/bin/python2.7
### allows to send data to STDIN of another process already running having STDIN attached to terminal
### FROM: https://stackoverflow.com/a/29616465/3295944
### but it doesn't work (fail process command line argument), but fixed here
'''
Here is how you use it:
Terminal #1: do...
$ tty > /tmp/t1
Terminal #2: do...
$ sudo python termfake.py $(cat /tmp/t1) date +%s
Terminal #1: observe...
$ tty > /tmp/t1
$ date +%s
1487276400
'''
import sys
import fcntl
import termios
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('tty', type=argparse.FileType('w'), help='full tty path as given by the tty command')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true', help='prevent sending a trailing newline character')
group.add_argument('--stdin', action='store_true', help='read input from stdin')
group = parser.add_argument_group()
group.add_argument('cmd', nargs='?', help='command to run (required if not using --stdin)')
group.add_argument('args', nargs='*', help='arguments to command')
##### ORIGINAL CODE WAS:
#args = parser.parse_known_args()
#if args.stdin:
# data = sys.stdin.read()
#else:
# data = ' '.join([args.cmd] + args.args)
#for c in data:
# fcntl.ioctl(args.tty, termios.TIOCSTI, c)
#if not args.n and data[-1][-1] != '\n':
# fcntl.ioctl(args.tty, termios.TIOCSTI, '\n')
#############
argstuple = parser.parse_known_args()
#print type(argstuple)
#print "this is a args tuple: %s" % (argstuple,)
#namespace, args = parser.parse_known_args()
namespace, args = argstuple
#print type(namespace)
#print type(args)
if namespace.stdin:
data = sys.stdin.read()
else:
data = ' '.join([namespace.cmd] + args)
#print type(data)
#print data
for c in data:
fcntl.ioctl(namespace.tty, termios.TIOCSTI, c)
if not namespace.n and data[-1][-1] != '\n':
fcntl.ioctl(namespace.tty, termios.TIOCSTI, '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment