Home > Back-end >  How to pipe command's output to program and keep its stdin open
How to pipe command's output to program and keep its stdin open

Time:11-10

for example, I want to to send `print(32) to python and it should print 32 and remain open until I press ctrl d

I did following

echo 'print(32)' | python

but It just prints 32 and closes the python.

I which to keep python's interactive shell open so I can futher send command to it with my keyboard.

EDIT: that was just example. instead of python it could be node, ruby or docker exec -it command.

basically I want to pipe output as if I was typing via my keyboard

CodePudding user response:

Use the -i flag to ask python to inspect interactively after running a script, combine with process substitution <(..) construct in bash. This will let the python command assume the commands are coming from a file even though it isn't

python -i <(echo 'print(32)')
32
>>>

or set the PYTHONINSPECT variable to a non-empty string to emulate the -i behavior

PYTHONINSPECT=x python <(echo 'print(32)')

Note that Process substitution is not supported in POSIX mode, but on bash/zsh or ksh93 only.

CodePudding user response:

If you are in xwindow with xdotool install, the behaviour can be simulated with :

#!/bin/bash
        
feed_initial_input(){
    local initial_input="$1"; shift
    { sleep 0.3; xdotool type "$initial_input"$'\n'; } &
    "$@"
}

feed_initial_input "print(32)" python
feed_initial_input "console.log('Hello world!')" node
  • Related