从 `stdin` 读取文件后如何使用 `input()`?
How to use `input()` after reading a file from `stdin`?
上下文
我想要一个简单的脚本 selects 1 of multiple piped inputs without EOF when reading a line
error on Unix/Linux.
它试图:
- 接受多行管道文本
- 等待用户select一个选项
- 将该选项打印到标准输出
所需用法:
$ printf "A\nB" | ./select.py | awk '{print "OUTPUT WAS: " [=10=]}'
Select 0-1:
0) A
1) B
> 1
OUTPUT WAS: B
末尾的 awk '{print "[OUTPUT WAS] " [=17=]}'
只是为了表明唯一的标准输出输出应该是 selection。
当前方法:
#!/bin/python3
import sys
from collections import OrderedDict
def print_options(options):
"""print the user's options"""
print(f"Select 0-{len(options)-1}:", file=sys.stderr)
for n, option in options.items():
print(f" {n}) {option}", file=sys.stderr)
def main():
# options are stored in an ordered dictionary to make order consistent
options = OrderedDict()
# read in the possible options one line at a time
for n, line in enumerate(sys.stdin):
options[n] = line.rstrip('\n')
valid_selection = False
# loop until we get a valid selection
while not valid_selection:
print_options(options)
try:
print('> ', end='', file=sys.stderr)
selection = int(input()) # <- doesn't block like it should
# use the selection to extract the output that will be printed
output = options[selection]
valid_selection = True
except Exception as e:
print(f"Invalid selection. {e}", file=sys.stderr)
print(output)
if __name__ == '__main__':
main()
错误:
脚本陷入无限循环打印:
...
> Invalid selection. EOF when reading a line
Select 0-1:
0) A
1) B
> Invalid selection. EOF when reading a line
Select 0-1:
0) A
1) B
> Invalid selection. EOF when reading a line
...
重现错误的最小脚本:
#!/bin/python3
import sys
options = []
# read in the possible options one line at a time
for line in sys.stdin:
options.append(line.rstrip('\n'))
user_input = input('> ')
print(user_input)
这抛出:
EOFError: EOF when reading a line
当我想看的时候输入:
$ printf "text" | ./testscript.py
> sometext
sometext
所需的解决方案:
我认为这是因为标准输入已达到 EOF。但我的问题是如何 reset/remove EOF 的影响,以便 input()
再次像往常一样阻塞并等待用户。
简而言之:如何在从 stdin
读取文件后使用 input()
?
如果那是不可能的,as this answer implies,有什么优雅的解决方案可以实现与我在这个问题开头描述的类似的行为?我对非 python 解决方案持开放态度(例如 bash|zsh、rust、awk、perl)。
我可以回答您 Linux/Unix OS 的问题。抱歉,我不使用 Windows。
我在你的示例代码中添加了两行,见下文。
特殊设备 /dev/tty
已连接到您的终端。这是您的标准 input/output 除非重定向。基本上你想恢复你的标准输入连接到你的终端的状态。在低级别上,它使用文件描述符 0。close
关闭它,open
获取第一个空闲的,在这种情况下是 0.
import sys
options = []
# read in the possible options one line at a time
for line in sys.stdin:
options.append(line.rstrip('\n'))
# restore input from the terminal
sys.stdin.close()
sys.stdin=open('/dev/tty')
user_input = input('> ')
print(user_input)
是我需要的,这是最终脚本,以防有人想使用它。
用法
$ printf "A\nB\nC" | ./select.py | awk '{print "Selected: " [=10=]}'
Select 0-1:
0) A
1) B
2) C
> 2 <- your input
Selected: C
完整解决方案
#!/bin/python3
"""
A simple script to allow selecting 1 of multiple piped inputs.
Usage:
printf "A\nB" | ./choose.py
If your input is space separated, make sure to convert with:
printf "A B" | sed 's+ +\n+g' | ./choose.py
Source:
"""
import sys
from collections import OrderedDict
def print_options(options):
"""print the user's options"""
print(f"Select 0-{len(options)-1}:", file=sys.stderr)
for n, option in options.items():
print(f" {n}) {option}", file=sys.stderr)
def select_loop(options):
valid_selection = False
# loop until we get a valid selection
while not valid_selection:
print_options(options)
try:
print('> ', end='', file=sys.stderr)
selection = int(input())
# use the selection to extract the output that will be printed
output = options[selection]
valid_selection = True
except Exception as e:
print(f"Invalid selection. {e}", file=sys.stderr)
return output
def main():
# options are stored in an ordered dictionary to fix iteration output
options = OrderedDict()
# read in the possible options one line at a time
for n, line in enumerate(sys.stdin):
options[n] = line.rstrip('\n')
# restore input from the terminal
sys.stdin.close()
sys.stdin=open('/dev/tty')
# if only one option is given, use it immediately
output = options[0] if len(options) == 1 else select_loop(options)
print(output)
if __name__ == '__main__':
main()
上下文
我想要一个简单的脚本 selects 1 of multiple piped inputs without EOF when reading a line
error on Unix/Linux.
它试图:
- 接受多行管道文本
- 等待用户select一个选项
- 将该选项打印到标准输出
所需用法:
$ printf "A\nB" | ./select.py | awk '{print "OUTPUT WAS: " [=10=]}'
Select 0-1:
0) A
1) B
> 1
OUTPUT WAS: B
末尾的 awk '{print "[OUTPUT WAS] " [=17=]}'
只是为了表明唯一的标准输出输出应该是 selection。
当前方法:
#!/bin/python3
import sys
from collections import OrderedDict
def print_options(options):
"""print the user's options"""
print(f"Select 0-{len(options)-1}:", file=sys.stderr)
for n, option in options.items():
print(f" {n}) {option}", file=sys.stderr)
def main():
# options are stored in an ordered dictionary to make order consistent
options = OrderedDict()
# read in the possible options one line at a time
for n, line in enumerate(sys.stdin):
options[n] = line.rstrip('\n')
valid_selection = False
# loop until we get a valid selection
while not valid_selection:
print_options(options)
try:
print('> ', end='', file=sys.stderr)
selection = int(input()) # <- doesn't block like it should
# use the selection to extract the output that will be printed
output = options[selection]
valid_selection = True
except Exception as e:
print(f"Invalid selection. {e}", file=sys.stderr)
print(output)
if __name__ == '__main__':
main()
错误:
脚本陷入无限循环打印:
...
> Invalid selection. EOF when reading a line
Select 0-1:
0) A
1) B
> Invalid selection. EOF when reading a line
Select 0-1:
0) A
1) B
> Invalid selection. EOF when reading a line
...
重现错误的最小脚本:
#!/bin/python3
import sys
options = []
# read in the possible options one line at a time
for line in sys.stdin:
options.append(line.rstrip('\n'))
user_input = input('> ')
print(user_input)
这抛出:
EOFError: EOF when reading a line
当我想看的时候输入:
$ printf "text" | ./testscript.py
> sometext
sometext
所需的解决方案:
我认为这是因为标准输入已达到 EOF。但我的问题是如何 reset/remove EOF 的影响,以便 input()
再次像往常一样阻塞并等待用户。
简而言之:如何在从 stdin
读取文件后使用 input()
?
如果那是不可能的,as this answer implies,有什么优雅的解决方案可以实现与我在这个问题开头描述的类似的行为?我对非 python 解决方案持开放态度(例如 bash|zsh、rust、awk、perl)。
我可以回答您 Linux/Unix OS 的问题。抱歉,我不使用 Windows。
我在你的示例代码中添加了两行,见下文。
特殊设备 /dev/tty
已连接到您的终端。这是您的标准 input/output 除非重定向。基本上你想恢复你的标准输入连接到你的终端的状态。在低级别上,它使用文件描述符 0。close
关闭它,open
获取第一个空闲的,在这种情况下是 0.
import sys
options = []
# read in the possible options one line at a time
for line in sys.stdin:
options.append(line.rstrip('\n'))
# restore input from the terminal
sys.stdin.close()
sys.stdin=open('/dev/tty')
user_input = input('> ')
print(user_input)
用法
$ printf "A\nB\nC" | ./select.py | awk '{print "Selected: " [=10=]}'
Select 0-1:
0) A
1) B
2) C
> 2 <- your input
Selected: C
完整解决方案
#!/bin/python3
"""
A simple script to allow selecting 1 of multiple piped inputs.
Usage:
printf "A\nB" | ./choose.py
If your input is space separated, make sure to convert with:
printf "A B" | sed 's+ +\n+g' | ./choose.py
Source:
"""
import sys
from collections import OrderedDict
def print_options(options):
"""print the user's options"""
print(f"Select 0-{len(options)-1}:", file=sys.stderr)
for n, option in options.items():
print(f" {n}) {option}", file=sys.stderr)
def select_loop(options):
valid_selection = False
# loop until we get a valid selection
while not valid_selection:
print_options(options)
try:
print('> ', end='', file=sys.stderr)
selection = int(input())
# use the selection to extract the output that will be printed
output = options[selection]
valid_selection = True
except Exception as e:
print(f"Invalid selection. {e}", file=sys.stderr)
return output
def main():
# options are stored in an ordered dictionary to fix iteration output
options = OrderedDict()
# read in the possible options one line at a time
for n, line in enumerate(sys.stdin):
options[n] = line.rstrip('\n')
# restore input from the terminal
sys.stdin.close()
sys.stdin=open('/dev/tty')
# if only one option is given, use it immediately
output = options[0] if len(options) == 1 else select_loop(options)
print(output)
if __name__ == '__main__':
main()