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.
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: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