File as command line argument for argparse - error message if argument is not valid

前端 未结 3 1883
夕颜
夕颜 2021-02-01 00:50

I am currently using argparse like this:

import argparse
from argparse import ArgumentParser

parser = ArgumentParser(description=\"ikjMatrix multiplication\")
p         


        
3条回答
  •  时光说笑
    2021-02-01 00:56

    A way to do this in Python 3.4 is to use the argparse.FileType class. Make sure to close the input stream when you are finished. This is also useful because you can use the pseudo-argument '-' for STDIN/STDOUT. From the documentation:

    FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects

    Example:

    #!/usr/bin/env python3
    
    import argparse
    
    if __name__ == '__main__':
      parser = argparse.ArgumentParser()
      parser.add_argument('--infile', type=argparse.FileType('r', encoding='UTF-8'), 
                          required=True)
      args = parser.parse_args()
      print(args)
      args.infile.close()
    

    And then when ran...

    • Without argument:

      $ ./stack_overflow.py
      usage: stack_overflow.py [-h] --infile INFILE
      stack_overflow.py: error: the following arguments are required: --infile
      
    • With nonexistent file:

      $ ./stack_overflow.py --infile notme
      usage: stack_overflow.py [-h] --infile INFILE
      stack_overflow.py: error: argument --infile: can't open 'notme': [Errno 2] No such file or directory: 'notme'
      
    • With an existing file:

      $ ./stack_overflow.py --infile ./stack_overflow.py
      Namespace(infile=<_io.TextIOWrapper name='./stack_overflow.py' mode='r' encoding='UTF-8'>)
      
    • Using '-' for STDIN:

      $ echo 'hello' | ./stack_overflow.py --infile -
      Namespace(infile=<_io.TextIOWrapper name='' mode='r' encoding='UTF-8'>)
      

提交回复
热议问题