Python命令行'文件输入流' [英] Python command line 'file input stream'

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

问题描述

来自C / C ++的python相当新,我想知道如何让我的'main.py'重新调整/使用从bash shell给出的输入:


python main.py< text.txt

(该文件是纯文本的)

解决方案

我会使用 argparse 创建一个选项解析器接受文件路径并打开它。

  import argparse 

def main():
parser = argparse.ArgumentParser()
parser.add_argument('infile',type ='open')
args = parser.parse_args()

for line in args.infile:
print line
$ b $ if if __name__ =='__main__':
main()

如果 type ='open'没有提供足够的控制,可以用 argparse替换。 FileType('o')它接受 bufsize mode args(参见 http://docs.python.org/dev/library/argparse.html#type



编辑:我的错误。这将不是支持您的用例。这将允许您提供文件路径,但不会将文件内容传送到进程中。我会在这里留下这个答案,因为它可能是有用的替代。


I'm fairly new to python coming from C/C++, I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as:

python main.py < text.txt

(the file is in plain text)

解决方案

I would use argparse to create an option parser that accepts a file path and opens it.

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type='open')
    args = parser.parse_args()

    for line in args.infile:
        print line

if __name__ == '__main__':
    main()

If type='open' does not provide enough control, it can be replaced with argparse.FileType('o') which accepts bufsize and mode args (see http://docs.python.org/dev/library/argparse.html#type)

EDIT: My mistake. This will not support your use case. This will allow you to provide a filepath, but not pipe the file contents into the process. I'll leave this answer here as it might be useful as an alternative.

这篇关于Python命令行'文件输入流'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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