Jiew Meng
Jiew Meng

Reputation: 88187

Python argparse & Unix piping to arguments

Suppose I want the output from rsgen.py to be used as the references argument of my simulate.py script. How can I do it?

In simulate.py

parser.add_argument("references", metavar="RS", type=int, nargs="+", help="Reference string to use")

I tried

# ./simulate.py references < rs.txt 
usage: simulate.py [-h] [--numFrames F] [--numPages P] RS [RS ...]
simulate.py: error: argument RS: invalid int value: 'references'

# ./simulate.py < rs.txt 
usage: simulate.py [-h] [--numFrames F] [--numPages P] RS [RS ...]
simulate.py: error: too few arguments

I believe my piping syntax is wrong, how can I fix it?

Idealy, I want to directly pipe the output from rsgen.py into the references argument of simulate.py

Upvotes: 2

Views: 3268

Answers (2)

rahmu
rahmu

Reputation: 5878

If you need to give the output of rsgen.py as an argument, your best solution is to use command substitution. The syntax varies according to the shell you're using, but the following will work on most modern shells:

./simulate.py references $(./rsgen.py) 

Side note, Brian Swift's answer uses backticks for command substitution. The syntax is valid on most shells as well, but has the disadvantage of not nesting really well.

On the other hand, if you want to pipe the output of a script into another, you should read from sys.stdin

Example:

a.py

print "hello world"

b.py

import sys

for i in sys.stdin:
    print "b", i

result:

$ ./a.py | ./b.py
b hello world

Upvotes: 3

Brian Swift
Brian Swift

Reputation: 1443

If you mean you want to use the output of rsgen.py as command line parameters to simulate.py, use backquotes which run the contained command and place the output into the command line

    ./simulate.py `./rsgen.py`

Upvotes: 3

Related Questions