Read from File, or STDIN

2019-01-21 02:52发布

I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage

tool -d character -f integer [filename]

How can I implement the following?

  • if a filename is given, read from the file.
  • if a filename is not given, read from STDIN.

7条回答
三岁会撩人
2楼-- · 2019-01-21 03:58

Not a direct answer but related.

Normally when you write a python script you could use the argparse package. If this is the case you can use:

parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

and here we set default to sys.stdin;

so If there is a file it will read it , and if not it will take the input from stdin "Note: that we are using positional argument in the example above"

for more visit: https://docs.python.org/2/library/argparse.html#nargs

查看更多
登录 后发表回答