Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from stdin or input file with argparse

I'd like to use argparse to read from either stdin or an input file. In other words:

  • If an input file is given, read that.
  • If not, read from stdin only if it's not the terminal. (i.e. a file is being piped in)
  • If neither of these criteria are satisfied, signal to argparse that the inputs aren't correct.

I'm asking for behavior similar to what's described in this question, but I want argparse to recognize no file as a failed input.

like image 526
Shep Avatar asked Oct 22 '22 10:10

Shep


2 Answers

I would recommend just settings nargs='?' and then handling the case of a Nonetype separately. According to the official 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". So just give it a dash if you want stdin.

Example

import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('inputfile', nargs='?', type=argparse.FileType('r'))
if not inputfile:
    sys.exit("Please provide an input file, or pipe it via stdin")
like image 85
lindhe Avatar answered Oct 24 '22 11:10

lindhe


Using the information from the question you linked to, what about using sys.stdin.isatty() to check if the instance your program is being run is part of a pipeline, if not, read from input file, otherwise read from stdin. If the input file does not exist or stdin is empty throw an error.

Hope that helped.

like image 38
Samuel Tan Avatar answered Oct 24 '22 10:10

Samuel Tan