Python-argparse&;Unix管道到参数
假设我希望Python-argparse&;Unix管道到参数,python,unix,pipe,command-line-arguments,argparse,Python,Unix,Pipe,Command Line Arguments,Argparse,假设我希望rsgen.py的输出用作脚本的引用参数。我怎么做 在simulate.py中 parser.add_argument("references", metavar="RS", type=int, nargs="+", help="Reference string to use") 我试过了 # ./simulate.py references < rs.txt usage: simulate.py [-h] [--numFrames F] [--numPages P] RS
rsgen.py
的输出用作脚本的引用
参数。我怎么做
在simulate.py中
parser.add_argument("references", metavar="RS", type=int, nargs="+", help="Reference string to use")
我试过了
# ./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
#./simulate.py引用
我相信我的管道语法是错误的,我如何修复它
理想情况下,我想将rsgen.py
的输出直接导入simulate.py
的references
参数中。如果您想将rsgen.py的输出用作simulate.py的命令行参数,请使用反引号运行包含的命令并将输出放入命令行
parser.add_argument("references", metavar="RS", type=int, nargs="+", help="Reference string to use")
./simulate.py `./rsgen.py`
如果需要将rsgen.py
的输出作为参数,最好的解决方案是使用。语法根据您使用的shell而有所不同,但以下内容适用于大多数现代shell:
./simulate.py references $(./rsgen.py)
另请注意,Brian Swift的回答使用反勾号替换命令。这种语法在大多数shell上也是有效的,但缺点是嵌套不太好
另一方面,如果要将脚本的输出通过管道传输到另一个脚本,则应该从sys.stdin
例如:
a.py
print "hello world"
import sys
for i in sys.stdin:
print "b", i
b.py
print "hello world"
import sys
for i in sys.stdin:
print "b", i
结果:
$ ./a.py | ./b.py
b hello world
另一种语法是imho的$./simulate.py$(rsgen.py)$./rsgen.py |./simulate.py更好。这是将程序输出转换为命令行参数的最简单和最受广泛支持的shell语法。您不需要担心用例的嵌套或其他问题。但是,如果rsgen的输出非常大,就不要使用它:在这种情况下,使用管道并从stdin读取simulate.py。在python 3中,它会像这样导入sys[NEWLINE]以获得sys.stdin:[NEWLINE]print中的行(“####”,line)