简体   繁体   English

Python - 如何从 shell 读取标准输入,并将标准输出发送到 shell 和文件

[英]Python - how can I read stdin from shell, and send stdout to shell and file

I'd like to have a Python script read stdin from the shell (bash), and send stdout to shell as well a redirected file.我想要一个 Python 脚本从 shell (bash) 读取标准输入,并将标准输出发送到 shell 以及重定向文件。 I tried the following:我尝试了以下方法:

$ cat test.py
#!/usr/bin/python

val = raw_input("enter val: ")
print val

$ ./test.py | tee out
testing
enter val: testing

$ cat out
enter val: testing

For some reason, the raw_input prompt is printed after I type my input, which means I can't see the prompt as I type.出于某种原因,在我输入输入后会打印 raw_input 提示,这意味着我在输入时看不到提示。 With a bash script, I can get something similar to work.使用 bash 脚本,我可以获得类似的工作。

$ cat test.sh
#!/bin/bash

echo "enter val: "
read val
echo $val

$ ./test.sh | tee out
enter val: testing
testing

$ cat out
enter val: testing
#!/usr/bin/python
import sys

print "enter val: ",
sys.stdout.flush()
val = raw_input()
print val

Or或者

#!/usr/bin/python
import sys

sys.stdout = sys.stderr
val = raw_input("enter val: ")
sys.stdout = sys.__stdout__
print val

See this bug, looks like raw_input writes its prompt to stderr.看到这个错误,看起来 raw_input 将其提示写入标准错误。

http://bugs.python.org/issue1927 http://bugs.python.org/issue1927

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python代码将stdin和stdout重定向到Shell脚本 - Python code to redirect stdin and stdout to a shell script 如何从 stdin 执行 shell 脚本并使用 python 实时获取 output? - How can I execute a shell script from stdin and get the output in realtime using python? 在 python 中,我如何仅打印由 shell 命令产生的标准输出的第一行 - In python how can i print only the first line of stdout which results from a shell command 从python控制Shell stdin - Controlling shell stdin from python Python-使用Shell的stdin和stdout生成/运行新进程 - Python - Spawn/Run a New Process Using Shell's stdin and stdout 如何运行只能写入STDOUT并从STDIN读取的脚本? - How to run a script that can only write to STDOUT and read from STDIN? 如何在进程stdin 仍在运行时写入进程stdin 并从其stdout 中读取? - how can I write to a processes stdin and read from its stdout while it is still running? 我正在 python 中制作 shell 但我无法读取它然后从文件中执行一行 - I'm making a shell in python but I can't get it to read then execute a line from a file 将StdIn重定向到python manage.py shell时从StdIn读取输入 - Read input from StdIn when redirecting StdIn to python manage.py shell 如何在远程 shell 的上下文中对 pdb 进行 stdin/stdout 重定向? - How to make stdin/stdout redirection of pdb, in the context of a remote shell?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM