[Tutor] how to redirect input from pipe

Peter Otten __peter__ at web.de
Wed Mar 22 20:38:37 EDT 2017


Yosef Levy wrote:

> Hello All,
> 
> I am running with Python 2.7
> I have to run script that could have get arguments in two ways:
> 1. argument + file name.
> 2. argument + input from pipe.
> 
> example for 1:
> ./my_script.py -t 1,2,3 file_name.txt
> 
> example for 2:
> grep snd file_name.txt | ./my_script.py -t 1,2,3
> 
> I am using "parse_known_args" to parse the rest of args when pipe exists.
> and capture with: "fileinput".
> 
> My problem is that this does not run always, for second option.
> Any idea how could I get standard input with additional flag?
> for example, running with pipe option will be like this:
> grep snd file_name.txt | ./my_script.py -t 1,2,3 -
> where the additional "-" at the end will indicate script to get standard
> input.

It's not clear to me why you use parse_known_args(). The examples you give 
above seem to be covered by

$ cat tmp.py
#!/usr/bin/env python
import argparse
import fileinput

parser = argparse.ArgumentParser()
parser.add_argument("--tags", "-t")
parser.add_argument("files", metavar="file", nargs="*")
args = parser.parse_args()

print args.tags
for line in fileinput.input(args.files):
    print line.strip()
$ cat greek.txt 
alpha
beta
gamma
delta
$ cat numbers.txt 
ONE
TWO

Reading from a file:

$ ./tmp.py -t 1,2,3 numbers.txt 
1,2,3
ONE
TWO

Reading from two files:

$ ./tmp.py -t 1,2,3 numbers.txt greek.txt 
1,2,3
ONE
TWO
alpha
beta
gamma
delta

Reading from stdin:

$ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3
1,2,3
alpha
beta

Reading from a file, then stdin, then another file:

$ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3 numbers.txt - numbers.txt 
1,2,3
ONE
TWO
alpha
beta
ONE
TWO
$ 




More information about the Tutor mailing list