Python command line 'file input stream'

2019-02-16 17:43发布

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)

3条回答
Summer. ? 凉城
2楼-- · 2019-02-16 18:20

Read from sys.stdin:

import sys
sys.stdin.read()

Being a file-like object, you can use its reading functions or simply iterate over the input lines:

for line in sys.stdin:
    print line
查看更多
Rolldiameter
3楼-- · 2019-02-16 18:25

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.

查看更多
做自己的国王
4楼-- · 2019-02-16 18:33

Using the fileinput module would be most appropriate here, and more flexible.

http://docs.python.org/library/fileinput.html

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

In addition to supporting stdin, it can also read from files listed as arguments.

查看更多
登录 后发表回答