繁体   English   中英

Argparse可选的stdin读取和/或stdout输出

[英]Argparse optional stdin read and/or stdout out

非Python程序将同时使用输入和输出参数来调用Python程序。 输入可以是文件引用,也可以是在非Python程序中重定向到stdin的字符串。 输出可能是文件或标准输出。

argparse.FileType似乎已准备好处理此问题,因为它已经具有特殊功能-可以直接指向stdin / stdout。 实际上,使用-定向到stdout可以,但是我不知道stdin的实现/语法。

非Python代码中的示例调用:
python mycode.py - output.txt
python mycode.py - -

之后,非Python代码会做什么? 打印/输出一个输入字符串?
之后,Python代码做什么?

我将始终需要区分两个arg的default=sys.stdin (即输入和输出),因此在add_argument使用default="-"default=sys.stdin add_argument都不起作用,因为它们需要一个不存在的参数。

这是我到目前为止的内容:

parser = argparse.ArgumentParser()

parser.add_argument('read_fref', type=argparse.FileType('r'))
parser.add_argument('write_fref', type=argparse.FileType('w'))
parser_ns = parser.parse_args()

with parser_ns.read_fref as f_r:
    read_f = json.load(f_r)    

output = {'k': 'v'}

with parser_ns.write_fref as f_w:
    json.dump(output, f_w)

我无法理解您的要求。 我了解Python和argparse在做什么,但是我不太了解您正在尝试做什么。

从Linux shell调用时,您的示例看起来运行良好。 使用-参数,它应该接受来自键盘的输入,并将其显示在屏幕上。 但是这些参数最常与shell重定向控件>, <, | (具体细节取决于shell, shbash等)。

但是,如果您使用外壳将stdinstdout重定向到文件或从文件重定向,则可以将这些文件作为命令行参数来使用。

如果您被必需/默认问题所困扰,请考虑将这些参数标记为(也称为optionals ):

parser.add_argument('-r','--readfile', type=argparse.FileType('r'), default='-')
parser.add_argument('-w','--writefile', type=argparse.FileType('w'), default='-')

进行此更改后,这些调用是相同的

python mycode.py -r - <test.json
python mycode.py <test.json
python mycode.py -r test.json

全部写入屏幕(stdout)。 可以通过类似的方式重定向。

要输入输入内容:

python mycode.py
{...}
^D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM