问题描述
来自C / C ++的python相当新,我想知道如何让我的'main.py'重新调整/使用从bash shell给出的输入:(该文件是纯文本的)
我会使用创建一个选项解析器接受文件路径并打开它。
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:
(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命令行'文件输入流'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!