0

I'm implementing a tool (java program) that embeds some command interpreters, as "bc", "sage", ... . The tool executes the interpreter in a thread, redirects its stdin and stdout, and writes some commands to the redirected stdin of the embedded interpreter (along time). Everything ok with "bc" and "sage" after solving usual problems with buffering.

In case of python, it seems that the interpreter is not reading its commands from stdin (I've verified that with a simple echo 1+2 | python ).

I do not find how to instruct the python interpreter to read its commands from stdin. I've read lots of similar questions, but all them tries to read data from stdin, not commands.

Note the command send to the python interpreter can be multi-line (a python "for" loop, ...) and commands are not yet available when python starts, they are generated and send to the interpreter along time.

In short, I want use python as a repl (read-eval-print-loop), reading from stdin.

pasaba por aqui
  • 3,446
  • 16
  • 40
  • Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Dec 14 '18 at 17:48
  • `python -c "1+1"` – Josef Korbel Dec 14 '18 at 17:58

1 Answers1

2

The python REPL mode is intended to be interactive and only works when it detects a terminal. You can pass commands into stdin, but they don't automatically print, you have to specify that. Try running

echo print 1+2 | python

That should get your expected result. You can also write your code to a file like this

echo print 1+2 > myfile
python myfile.py

It is also possible to use a buffer like a fifo node to pass data to python's stdin, but python exits after every line, and you get no advantage over simply running "echo print 1+2 | python".

mkfifo a=rw MYFIFO
echo "print 1+2" > MYFIFO &
cat MYFIFO | python".

Using python the expected way, by executing each set of code as you need it, should work better than keeping a repl open, and will produce more consistent results.

user39098
  • 36
  • 2