在 python 中,以下代码将让我们写入 stdout
:
import sys
sys.stdout.write("blah %d" % 5)
但是,我希望能够灵活地选择打印到哪个流。我想将流作为参数传递到函数中,就像在任何 C
派生语言中调用 fprintf
时一样。在上面的源代码片段中,stdout
被硬编码到 write 语句中。但是,我们希望能够灵活地选择写入哪个流。我们可能需要 stderr
或其他一些流来代替 stdout
。
最佳答案
你说
I want to pass the stream as an argument into a function
但这并没有给你任何额外的灵活性。如果您有一个 some_stream
变量引用您想要写入的流,那么您已经可以这样做
some_stream.write("blah %d" % 5)
因此,将流作为函数参数不会获得任何好处。也就是说,print
函数采用一个 file
参数来指定要写入哪个流:
print("blah %d" % 5, end='', file=some_stream)
关于python - 在 python 中实现 fprintf 的简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991861/