When writing text-oriented command line programs in Python, I often want to read either all the files passed on the command line, or (XOR) standard input (like Unix cat
does, or Perl's <>
). So, I say
if len(args) == 0: # result from optparse
input = sys.stdin
else:
input = itertools.chain(*(open(a) for a in args))
Is this the Pythonic way of doing this, or did my miss some part of the library?
1. Reading Python Command-line arguments using the sys module The command-line arguments are stored in the sys module argv variable, which is a list of strings. We can read the command-line arguments from this list and use it in our program. Note that the script name is also part of the command-line arguments in the sys.argv variable.
This can be either reading from the console directly or reading from the filename specified in the console. We can use the fileinput module to read from stdin in Python. fileinput.input () reads through all the lines in the input file names specified in command-line arguments.
The command-line arguments are used to provide specific inputs to the program. What is the benefit of Python Command Line Arguments? Python command-line arguments help us to keep our program generic in nature.
When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples. With the 'store_const' and 'append_const' actions, the const keyword argument must be given. For other actions, it defaults to None.
You need fileinput.
A standard use case is:
import fileinput
for line in fileinput.input():
process(line)
See
How do you read from stdin in Python?
In Python 3, argparse
handles filetype objects very nicely. It's an extremely powerful module and the docs come with many examples, so it's easy to quickly write the code you want. (How Pythonic!)
You may also benefit from this StackOverflow question about using argparse
to optionally read from stdin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With