gpt4 book ai didi

python - python 会接受 - (破折号)作为 `open()` 的文件名写入标准输出吗?

转载 作者:行者123 更新时间:2023-12-05 02:58:31 25 4
gpt4 key购买 nike

我正在使用一个接受输出文件作为参数的 Python 脚本。它使用 open(outfile, "w") 打开并写入该文件。

Linux 中的一个常见约定是使用 -(破折号)写入标准输出。 It is a common convention but not standard nor part of a shell.

我可以将 - 作为输出文件名传递,以便 Pythons open 写入标准输出吗?

最佳答案

不,标准库open() function不会将文件名 '-' 转换为 stdinstdout。它只是一个普通文件名,因此open("-", "w") 将写入当前工作目录中名为-.

您必须显式测试该值,因此返回 sys.stdinsys.stdout(取决于您需要读取或写入的内容),而不是打开文件。

例如click command-line interface library ,这supports using - as a filename on the command line , 在其 open_stream() implementation 中显式测试 '-' 文件名:

if filename == '-':
if any(m in mode for m in ['w', 'a', 'x']):
if 'b' in mode:
return get_binary_stdout(), False
return get_text_stdout(encoding=encoding, errors=errors), False
if 'b' in mode:
return get_binary_stdin(), False
return get_text_stdin(encoding=encoding, errors=errors), False

open() 确实接受 file handles ,所以你可以为标准输入传入 0,或者为标准输出传入 1:

>>> inp = open(0)
>>> inp
<_io.TextIOWrapper name=0 mode='r' encoding='UTF-8'>
>>> inp.read(1) # read 1 character from stdin, I entered 'a'
a
'a'
>>> outp = open(1, 'w')
>>> outp
<_io.TextIOWrapper name=1 mode='w' encoding='UTF-8'>
>>> outp.write("foo!") # line buffered, no newline written so not visible yet
4
>>> outp.flush() # flush the buffer
foo!>>>

关于python - python 会接受 - (破折号)作为 `open()` 的文件名写入标准输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58962722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com