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
JavaScript
x
2
1
tool -d character -f integer [filename]
2
How can I implement the following?
- if a filename is given, read from the file.
- if a filename is not given, read from STDIN.
Advertisement
Answer
In the simplest terms:
JavaScript
1
7
1
import sys
2
# parse command line
3
if file_name_given:
4
inf = open(file_name_given)
5
else:
6
inf = sys.stdin
7
At this point you would use inf
to read from the file. Depending on whether a filename was given, this would read from the given file or from stdin.
When you need to close the file, you can do this:
JavaScript
1
3
1
if inf is not sys.stdin:
2
inf.close()
3
However, in most cases it will be harmless to close sys.stdin
if you’re done with it.