Argparse 可选的标准输入读取和/或标准输出输出

Eri*_*c S 4 python stdin stdout argparse

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

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

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

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

我将始终需要区分两个 args 的去向(即输入和输出),因此使用default="-"default=sys.stdininadd_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)
Run Code Online (Sandbox Code Playgroud)

hpa*_*ulj 7

我很难理解你在问什么。我了解 Python 和argparse正在做什么,但我不太明白您要做什么。

当从 Linux shell 调用时,您的示例看起来可以正常运行。使用-参数,它应该接受来自键盘的输入,并将其显示在屏幕上。但这些参数最常与 shell 重定向控件一起使用>, <, |(详细信息因 shell shbash、 等而异)。

但是,如果您使用 shell 重定向文件stdinstdout从文件重定向到/从文件,您也可以将这些文件作为命令行参数提供。

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

parser.add_argument('-r','--readfile', type=argparse.FileType('r'), default='-')
parser.add_argument('-w','--writefile', type=argparse.FileType('w'), default='-')
Run Code Online (Sandbox Code Playgroud)

有了这个变化,这些调用是相同的

python mycode.py -r - <test.json
python mycode.py <test.json
python mycode.py -r test.json
Run Code Online (Sandbox Code Playgroud)

所有写入屏幕(标准输出)。这可以以类似的方式重定向。

输入输入:

python mycode.py
{...}
^D
Run Code Online (Sandbox Code Playgroud)

  • 好的,我知道了。尝试了我需要的所有变体,包括读取标准输入,写入标准输出:`test.py -r - -w - &lt;in.txt` 并读取标准输入,写入文件:`test.py -r - -w out.txt &lt;in .txt`。谢谢你的时间! (2认同)