Your preprocess.py
文件正在尝试读取表单sys.argv[1]
并将其作为文件打开。
如果你通过了-h
对于您的命令行,它正在尝试打开具有该名称的文件。
将命令行解析与处理分开
Your preprocess
函数不应关心命令行参数,它应获取打开的文件描述符作为参数。
因此,在解析命令行参数后,您应该注意提供文件描述符,在您的情况下它将是sys.stdin
.
示例解决方案使用docopt
argparse 没有任何问题,我最喜欢的解析器是docopt
我将用它来说明命令行解析、准备最终函数调用和最终函数调用的典型拆分。您也可以使用 argparse 实现相同的目的。
首先安装docopt:
$ pip install docopt
来了fromstdin.py
code:
"""fromstdin - Training and Testing Framework
Usage: fromstdin.py [options] <input>
Options:
--text=<textmodel> Text model [default: text.txt]
--features=<features> Features model [default: features.txt]
--test=<testset> Testing set [default: testset.txt]
--vectorizer=<vectorizer> The vectorizec [default: vector.txt]
Read data from <input> file. Use "-" for reading from stdin.
"""
import sys
def main(fname, text, features, test, vectorizer):
if fname == "-":
f = sys.stdin
else:
f = open(fname)
process(f, text, features, test, vectorizer)
print "main func done"
def process(f, text, features, test, vectorizer):
print "processing"
print "input parameters", text, features, test, vectorizer
print "reading input stream"
for line in f:
print line.strip("\n")
print "processing done"
if __name__ == "__main__":
from docopt import docopt
args = docopt(__doc__)
print args
infile = args["<input>"]
textfile = args["--text"]
featuresfile = args["--features"]
testfile = args["--test"]
vectorizer = args["--vectorizer"]
main(infile, textfile, featuresfile, testfile, vectorizer)
可以这样调用:
$ python fromstdin.py
Usage: fromstdin.py [options] <input>
显示帮助:
$ python fromstdin.py -h
fromstdin - Training and Testing Framework
Usage: fromstdin.py [options] <input>
Options:
--text=<textmodel> Text model [default: text.txt]
--features=<features> Features model [default: features.txt]
--test=<testset> Testing set [default: testset.txt]
--vectorizer=<vectorizer> The vectorizec [default: vector.txt]
Read data from <input> file. Use "-" for reading from stdin.
使用它,从标准输入输入:
(so)javl@zen:~/sandbox/so/cmd$ ls | python fromstdin.py -
{'--features': 'features.txt',
'--test': 'testset.txt',
'--text': 'text.txt',
'--vectorizer': 'vector.txt',
'<input>': '-'}
processing
input parameters text.txt features.txt testset.txt vector.txt
reading input stream
bcmd.py
callit.py
fromstdin.py
scrmodule.py
processing done
main func done