从文件或标准输入读取 [英] Read from File, or STDIN

查看:80
本文介绍了从文件或标准输入读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了使用的getopt解析命令行上给定参数的命令行实用程序。我也想有一个文件名是一个可选的参数,如它在其他实用程序,如grep,剪切等,所以,我想它有以下用途

I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage

tool -d character -f integer [filename]

我如何能实现以下?

How can I implement the following?


  • 如果一个文件名给定,从文件中读取。

  • 如果没有给出一个文件名,从标准输入读取。

推荐答案

在最简单的术语:

import sys
# parse command line
if file_name_given:
    inf = open(file_name_given)
else:
    inf = sys.stdin

在这一点上,你会使用 INF 来从文件中读取。根据文件名是否被赋予,这会从给定的文件或标准输入读取。

At this point you would use inf to read from the file. Depending on whether a filename was given, this would read from the given file or from stdin.

当你需要关闭该文件,你可以这样做:

When you need to close the file, you can do this:

if inf is not sys.stdin:
    inf.close()

然而,在大多数情况下,如果你用它做无害关闭 sys.stdin

这篇关于从文件或标准输入读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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