Skip to content

Instantly share code, notes, and snippets.

@LewisGaul
Created September 9, 2019 09:28
Show Gist options
  • Save LewisGaul/f0ab8cb3ff27fc41a0f78d32fc124623 to your computer and use it in GitHub Desktop.
Save LewisGaul/f0ab8cb3ff27fc41a0f78d32fc124623 to your computer and use it in GitHub Desktop.
Example usage of 'sh' library, illustrating ability to interact over stdin
import os.path
import sh
from textwrap import dedent
this_line = []
nums = [4, 3, 2, 1]
def interact(char, stdin, process):
print(char, end='', flush=True)
if char == '\n':
#print('line:', ''.join(this_line))
this_line.clear()
return
this_line.append(char)
if 'Square a number: ' in ''.join(this_line):
try:
n = nums.pop(0)
#print('Putting', n)
stdin.put(str(n) + '\n')
except IndexError:
print('<Killing>')
process.signal(2)
return True # Stop calling this callback
finally:
this_line.clear()
pyfile = os.path.expanduser('~/tmp.py')
with open(pyfile, 'w') as f:
f.write(dedent(
"""
print("Starting")
while True:
n = input("Square a number: ")
print(int(n)**2)
"""
))
p = sh.python(pyfile, _bg=True, _out=interact, _ok_code=1, _out_bufsize=0)
p.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment