简体   繁体   中英

Execute commands from stdin to stdout without print statement like in REPL

What's the easiest way to make this work:

> echo 1+1 | [run python in REPL and exit with capturing all statement values to stdout ]
2

Yes, we can do echo "print(1+1)" | python echo "print(1+1)" | python but that requires to write print . The point is to make python behave like PowerShell:

> echo 1+1 | powershell -c -
2

Yes, we can do echo 1+1 | python -i echo 1+1 | python -i but that output some noise (python version etc.).

The following is not a recommended practice, since it uses the unsafe eval function. However, in the context of what you are asking for, where you seem to have control of all the steps in the process, it will do.

Write the following simple Python program ( my_program.py ):

import sys

sys.stdout.write(str(eval(sys.stdin.read())))

Then, use:

> echo 1+1 | python my_program.py
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM