Python command line 'file input stream'

前端 未结 3 1424
小蘑菇
小蘑菇 2021-01-11 23:19

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:

pyth

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 00:22

    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.

提交回复
热议问题