Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read from command line arguments or stdin

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?

like image 366
Fred Foo Avatar asked Apr 15 '11 11:04

Fred Foo


People also ask

How do I read a command line argument in Python?

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.

How to read from stdin in Python?

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.

What is the use of 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.

How do I parse a string with no command-line argument?

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.


3 Answers

You need fileinput.

A standard use case is:

import fileinput
for line in fileinput.input():
  process(line)
like image 176
eumiro Avatar answered Oct 13 '22 06:10

eumiro


See

How do you read from stdin in Python?

like image 26
Andreas Jung Avatar answered Oct 13 '22 06:10

Andreas Jung


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.

like image 2
Michael Scheper Avatar answered Oct 13 '22 06:10

Michael Scheper