首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在读取“`stdin`”中的文件后使用“How ()”?

如何在读取“`stdin`”中的文件后使用“How ()”?
EN

Stack Overflow用户
提问于 2021-02-10 10:28:01
回答 2查看 248关注 0票数 1

上下文

我想要一个简单的脚本,在Unix/Linux上选择多个管道输入中的一个,而不会出现EOF when reading a line错误。

它试图:

  1. 接受多行管道文本
  2. 等待用户选择一个选项
  3. 打印该选项以输出

预期用途:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$ printf "A\nB" | ./select.py | awk '{print "OUTPUT WAS: " $0}'
Select 0-1:
  0) A
  1) B
> 1
OUTPUT WAS: B

最后的awk '{print "[OUTPUT WAS] " $0}'只是为了显示唯一的标准输出应该是选择。

现行办法:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/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()

错误:

脚本陷入无限循环打印:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
...
> 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
...

复制错误的最小脚本:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/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)

这会抛出:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
EOFError: EOF when reading a line

当我想看到和输入:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$ printf "text" | ./testscript.py
> sometext
sometext

所需解决办法:

我想这是由于stdin已经达到EOF的事实。但是我的问题是如何重置/删除EOF的影响,以便input()再次阻塞并像通常那样等待用户。

简单地说:在从input() stdin**?**读取文件之后,如何使用

如果这是不可能的,as this answer implies,有什么优雅的解决方案可以得到类似于我在这个问题开头描述的行为呢?我对非python解决方案(例如bash\zsh、锈病、awk、perl)持开放态度。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-10 11:18:24

我可以为Linux/Unix回答您的问题。对不起,我不使用Windows。

我在示例代码中添加了两行代码,如下所示。

特殊设备/dev/tty连接到您的终端。除非重定向,否则这是您的标准输入/输出。基本上,您希望恢复stdin连接到您的终端的状态。在较低的级别上,它使用文件描述符0。close关闭它,open获得第一个免费的,在这种情况下是0。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2021-02-10 11:24:04

VPfB's answer是我所需要的,这是最后定稿的脚本,以防有人想要使用它。

用法

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$ printf "A\nB\nC" | ./select.py | awk '{print "Selected: " $0}'
Select 0-1:
  0) A
  1) B
  2) C
> 2 <- your input
Selected: C

全解

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/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: https://stackoverflow.com/a/66143667/7872793
"""
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66142884

复制
相关文章
如何使用python读取txt文件中的数据
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139037.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/02
6.8K0
在Node.js中如何逐行读取文件
本文翻译自How to read a file line by line in Node.js
ccf19881030
2020/10/29
13.7K0
How to Use the Stdin, Stderr, and Stdout Streams in Bash
How to Use the Stdin, Stderr, and Stdout Streams in Bash – Linux Consultant
阿东
2023/03/16
2.8K0
How to Use the Stdin, Stderr, and Stdout Streams in Bash
使用Spring中的PropertyPlaceholderConfigurer读取文件
注意:我们知道不论是使用 PropertyPlaceholderConfigurer 还是通过 context:property-placeholder 这种方式进行实现,都需要记住,Spring框架不仅仅会读取我们的配置文件中的键值对,而且还会读取 Jvm 初始化的一下系统的信息。有时候,我们需要将配置 Key 定一套命名规则 ,例如
海向
2019/09/25
2K0
如何使用Python读取大文件
背景 最近处理文本文档时(文件约2GB大小),出现memoryError错误和文件读取太慢的问题,后来找到了两种比较快Large File Reading 的方法,本文将介绍这两种读取方法。 原味地址 准备工作 我们谈到“文本处理”时,我们通常是指处理的内容。Python 将文本文件的内容读入可以操作的字符串变量非常容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read
用户1217611
2018/03/29
5.1K0
python读取文件后诡异的\ufeff
    运行环境介绍:在python读取txt文档的时候在首行会出现诡异的\ufeff,对比字符串就会对比失败
py3study
2020/01/07
1.6K0
如何在 Python 中读取 .data 文件?
在本文中,我们将学习什么是 .data 文件以及如何在 python 中读取 .data 文件。
很酷的站长
2023/02/22
5.9K0
如何在 Python 中读取 .data 文件?
如何在Java中逐行读取文件
本文翻译自How to read a file line by line in Java
ccf19881030
2020/11/24
10.5K0
在Shell脚本中逐行读取文件的命令方法
为了演示,在此创建一个名为“ mycontent.txt”的文本文件,文件内容在下面:
用户7639835
2021/12/03
9.3K0
python中如何打开csv文件_python如何读取csv文件
python如何读取csv文件,我们这里需要用到python自带的csv模块,有了这个模块读取数据就变得非常容易了。
全栈程序员站长
2022/09/16
7.9K0
python中如何打开csv文件_python如何读取csv文件
如何使用 Python批量读取多个文件
可以看出,它会自动把你输入的内容打印出来,相当于在 whileTrue里面加上了 input。
青南
2019/09/16
10.5K0
使用CSV模块和Pandas在Python中读取和写入CSV文件
CSV文件是一种纯文本文件,其使用特定的结构来排列表格数据。CSV是一种紧凑,简单且通用的数据交换通用格式。许多在线服务允许其用户将网站中的表格数据导出到CSV文件中。CSV文件将在Excel中打开,几乎所有数据库都具有允许从CSV文件导入的工具。标准格式由行和列数据定义。此外,每行以换行符终止,以开始下一行。同样在行内,每列用逗号分隔。
用户7466307
2020/06/16
20.1K0
OpenCV中如何读取URL图像文件
最近知识星球收到的提问,觉得是一个很有趣的问题,就通过搜集整理归纳了一番,主要思想是通过URL解析来生成数据,转为图像/Mat对象。但是在Python语言与C++语言中的做法稍有不同。
OpenCV学堂
2019/07/19
5.9K0
如何在python中惰性地读取文件?
惰性地读取,就是在读文件的时候,不是直接将整个文件读到内存之中,而是一行一行的读取。这对于读取如网页日志这样的贼大的文件来说,可以减少打开文件的响应时间以及所占用的内存。
灯珑LoGin
2022/10/31
1.8K0
Nodejs中读取文件目录中的所有文件
关于Nodejs中的文件系统即File System可以参考官方Node.js v12.18.1的文档File system
ccf19881030
2020/06/28
14.8K0
在Node.js中逐行读取文件【纯技术】
在计算机科学中,文件是一种资源,用于在计算机的存储设备中离散地记录数据。Node.js不会以任何方式覆盖它,并且可以与文件系统中被视为文件的任何文件一起使用。
Jean
2019/09/24
7.8K0
在Python中按路径读取数据文件的几种方式
我们知道,写Python代码的时候,如果一个包(package)里面的一个模块要导入另一个模块,那么我们可以使用相对导入:
马哥Python
2019/07/15
20.4K0
在Python中按路径读取数据文件的几种方式
如何使用find命令在Linux中查找文件
Find是一个命令行实用程序,它允许您根据用户给定的表达式搜索目录层次结构中的文件和目录,并对每个匹配的文件应用用户指定的操作。
用户8704835
2021/06/08
5.1K0
如何使用LinkFinder在JavaScript文件中查找网络节点
LinkFinder是一款功能强大的Python脚本,在该工具的帮助下,广大研究人员可以轻松在JavaScript文件中发现和扫描网络节点及其相关参数。这样一来,渗透测试人员和漏洞猎人将能够快速在测试的目标网站伤收集新的隐藏节点了。
FB客服
2023/08/08
4460
如何使用LinkFinder在JavaScript文件中查找网络节点
点击加载更多

相似问题

读取文件后从stdin读取

20

在C中通过STDIN读取文件

14

使用scanf从stdin C中读取文件

22

使用awk从stdin或文件中读取

23

在使用"freopen“(在C中)后,如何将stdin改为从终端读取?

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文