非 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)