Search code examples
pythonbashargparse

How send parameters through a pipe in a python script using argparse?


I have to create a python script that can be used with Linux pipes

I want to run an script where some parameters can be send with a pipe or in the same line

Some examples of the use of my script with the expected output:

echo "a" > list.txt
echo "b" >> list.txt

./run.py p1 p2   # ['p1', 'p2'] expected output
cat list.txt | ./run.py  # ['a', 'b'] expected output
cat list.txt | ./run.py p1 p2 # ['p1', 'p2', 'a', 'b'] expected output

I tried:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args().args
print args

It works only with the parameters in the same line:

./run.py p1 p2  #['p1', 'p2'] OK
cat list.txt | ./run.py  # []  Not OK
cat list.txt | ./run.py p1 p2 # ['p1', 'p2'] expected output

Solution

  • A solution by using only argparse

    import argparse
    import sys
    
    parser = argparse.ArgumentParser()
    parser.add_argument('args', nargs=argparse.REMAINDER)
    parser.add_argument('stdin', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    args = parser.parse_args().args
    
    if not sys.stdin.isatty():
        stdin = parser.parse_args().stdin.read().splitlines()
    else:
        stdin = []
    
    print(args + stdin)
    

    nargs='?' makes stdin optional and sys.stdin.isatty() checks if sys.stdin is empty