如果没有数据通过Python传输,如何从stdin或文件中读取? [英] How to read from stdin or from a file if no data is piped in Python?

查看:86
本文介绍了如果没有数据通过Python传输,如何从stdin或文件中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CLI脚本,希望它从文件中读取数据.它应该可以通过两种方式阅读它:

I have a CLI script and want it to read data from a file. It should be able to read it in two ways :

  • cat data.txt | ./my_script.py
  • ./my_script.py data.txt
  • cat data.txt | ./my_script.py
  • ./my_script.py data.txt

-例如,类似于grep.

我所知道的:

  • sys.argvoptparse让我轻松阅读任何参数和选项.
  • sys.stdin让我读取通过管道传输的数据
  • fileinput使整个过程自动化
  • sys.argv and optparse let me read any args and options easily.
  • sys.stdin let me read data piped in
  • fileinput make the full process automatic

不幸的是:

  • 使用fileinput使用stdin和所有args作为输入.因此,在尝试打开非文件名的选项时,我将无法使用它们.
  • sys.stdin.readlines()正常工作,但是如果我不传送任何数据,它将挂起,直到我输入 Ctrl + D
  • 我不知道如何实现如果在stdin中什么都没有,请从args中的文件中读取",因为stdin在布尔上下文中始终为True.
  • using fileinput uses stdin and any args as input. So I can't use options that are not filenames as it tries to open them.
  • sys.stdin.readlines() works fine, but if I don't pipe any data, it hangs until I enter Ctrl + D
  • I don't know how to implement "if nothing in stdin, read from a file in args" because stdin is always True in a boolean context.

如果可能的话,我想用一种便携式的方法来做到这一点.

I'd like a portable way to do this if possible.

推荐答案

根据需要处理您的非文件名参数,因此最终得到一个非选项参数数组,然后将该数组作为参数传递给 fileinput.input() :

Process your non-filename arguments however you'd like, so you wind up with an array of non-option arguments, then pass that array as the parameter to fileinput.input():

import fileinput
for line in fileinput.input(remaining_args):
    process(line)

这篇关于如果没有数据通过Python传输,如何从stdin或文件中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆