我是靠谱客的博主 俏皮电源,最近开发中收集的这篇文章主要介绍python读取输入流,Python命令行'文件输入流',觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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读取输入流,Python命令行'文件输入流'的全部内容,希望文章能够帮你解决python读取输入流,Python命令行'文件输入流'所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部