从Stdin读取带有参数的Python [英] Python Read from Stdin with Arguments

查看:78
本文介绍了从Stdin读取带有参数的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从python stdin中读取内容,但也希望在程序中具有输入选项.当我尝试将选项传递给程序时,找不到错误文件,并且我的参数也被丢弃.

I want to read from python stdin but also to have input options in my program. When I try to pass an option to my programm I get the error file not found and my arguments are discarded.

为了解析参数,我使用以下代码:

For parsing the arguments I use the following code:

parser=argparse.ArgumentParser(description='Training and Testing Framework')

parser.add_argument('--text', dest='text',
                   help='The text model',required=True)
parser.add_argument('--features', dest='features',
                   help='The features model',required=True)
parser.add_argument('--test', dest='testingset',
                   help='The testing set.',required=True)
parser.add_argument('--vectorizer', dest='vectorizer',
                   help='The vectorizer.',required=True)
args = vars(parser.parse_args())

要从标准输入中读取,请使用以下代码:

For reading from the stdin I use the following code:

for line in sys.stdin.readlines():
    print(preprocess(line,1))

命令行

echo "dsfdsF" |python ensemble.py -h
/usr/local/lib/python2.7/dist-packages/pandas/io/excel.py:626: UserWarning: Installed openpyxl is not supported at this time. Use >=1.6.1 and <2.0.0.
  .format(openpyxl_compat.start_ver, openpyxl_compat.stop_ver))
Traceback (most recent call last):
  File "ensemble.py", line 38, in <module>
    from preprocess import preprocess
  File "/home/nikos/experiments/mentions/datasets/preprocess.py", line 7, in <module>
    with open(sys.argv[1], 'rb') as csvfile:
IOError: [Errno 2] No such file or directory: '-h'

推荐答案

您的preprocess.py文件正试图读取sys.argv[1]表格并将其作为文件打开.

Your preprocess.py file is trying to read form sys.argv[1] and open it as a file.

如果将-h传递到命令行,它将尝试打开具有该名称的文件.

If you pass -h to your command line, it is trying to open file with that name.

您的preprocess函数将不在乎命令行参数,它将获取打开文件描述符作为参数.

Your preprocess function shall not care about command line parameters, it shall get the open file descriptor as an argument.

因此,在解析命令行参数之后,您应该注意提供文件描述符,在您的情况下为sys.stdin.

So after you parse command line parameters, you shall take care about providing file descriptor, in your case it will be sys.stdin.

argparse没什么问题,我最喜欢的解析器是docopt,我将用它来说明典型的命令行解析拆分,准备最终函数调用和最终函数调用.您也可以使用argparse达到相同的效果.

There is nothing wrong with argparse, my favourite parser is docopt and I will use it to illustrate typical split of command line parsing, preparing final function call and final function call. You can achieve the same with argparse too.

首先安装docopt:

First install docopt:

$ pip install docopt

这是fromstdin.py代码:

"""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.

使用它,从标准输入中获取

Use it, feeding 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

这篇关于从Stdin读取带有参数的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆