从命令行参数或标准输入中读取Python [英] Python read from command line arguments or stdin

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

问题描述

在Python中编写面向文本的命令行程序时,我经常想读取在命令行上传递的所有文件,或者读取(XOR)标准输入(例如Unix cat ,或者Perl的<> )。所以,我说

When writing text-oriented command line programs in Python, I often want to read either all the files passed on the command line, or (XOR) standard input (like Unix cat does, or Perl's <>). So, I say

if len(args) == 0:  # result from optparse
    input = sys.stdin
else:
    input = itertools.chain(*(open(a) for a in args))

这是这样做的Python方式,还是我错过了库的某些部分?

Is this the Pythonic way of doing this, or did my miss some part of the library?

推荐答案

您需要文件输入

标准用例是:

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

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

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