[英]In a loop, optionally write output to files
I wrote a function which iteratively computes some quantities X,Y
, returning the final result.我写了一个函数,它迭代地计算一些量
X,Y
,返回最终结果。 Additionally, this code saves each iteration of X,Y
to a file.此外,此代码将
X,Y
的每次迭代保存到文件中。 Here is the basic structure:这是基本结构:
def myFunc():
X,Y = 0,0
file1 = open(output1,"w")
file2 = open(output2,"w")
for i in range(1000):
X,Y = someCalculation(X,Y) #calculations happen here
file1.write(X)
file2.write(Y)
file1.close()
file2.close()
return X,Y
However, if the filename output1
or output2
is omitted when the function is called, I need this function to perform the same calculation without appending anything to the relevant file .但是,如果在调用函数时省略了文件名
output1
或output2
,我需要这个函数来执行相同的计算,而不向相关文件附加任何内容。
Here is my messy solution:这是我的混乱解决方案:
def myFunc(output1=None,output2=None):
X,Y = 0,0
if (output1 != None): file1 = open(output1,"w")
if (output2 != None): file2 = open(output2,"w")
for i in range(1000):
X,Y = someCalculation(X,Y) #calculations happen here
if (output1 != None): file1.write(X)
if (output2 != None): file2.write(Y)
if (output1 != None): file1.close()
if (output2 != None): file2.close()
return X,Y
Is there a better, cleaner way to write this?有没有更好、更干净的方法来写这个?
Make a dummy file object that ignores writes, and supports the context manager interface:创建一个忽略写入的虚拟文件对象,并支持上下文管理器接口:
class NoFile:
def __enter__(self): return self
# Propagate any exceptions that were raised, explicitly.
def __exit__(self, exc_type, exc_value, exc_tb): return False
# Ignore the .write method when it is called.
def write(self, data): pass
# We can extend this with other dummy behaviours, e.g.
# returning an empty string if there is an attempt to read.
Make a helper function that creates one of these instead of a normal file when the filename is None
:当文件名
is None
时,创建一个辅助函数来创建其中一个而不是普通文件:
def my_open(filename, *args, **kwargs):
return NoFile() if filename is None else open(filename, *args, **kwargs)
Use with
blocks to manage the file lifetimes, as you should do anyway - but now use my_open
instead of open
:使用
with
块来管理文件生命周期,无论如何你都应该这样做 - 但现在使用my_open
而不是open
:
def myFunc(output1=None,output2=None):
X, Y = 0, 0
with my_open(output1, 'w') as f1, my_open(output2, 'w') as f2:
for i in range(1000):
X, Y = someCalculation(X, Y) #calculations happen here
f1.write(X)
f2.write(Y)
return X, Y
You can create a dummy class that has a do-nothing write
method.您可以创建一个具有无操作
write
方法的虚拟类。 ExitStack
is used to ensure any opened files are closed automatically. ExitStack
用于确保所有打开的文件都自动关闭。
from contextlib import ExitStack
class NoWrite:
def write(self, value):
pass
def myFunc(output1=None, output2=None):
X,Y = 0,0
with ExitStack() as es:
file1 = es.enter_context(open(output1, "w")) if output1 is not None else NoWrite()
file2 = es.enter_context(open(output2, "w")) if output2 is not None else NoWrite()
for i in range(1000):
X,Y = someCalculation(X, Y) #calculations happen here
file1.write(X)
file2.write(Y)
return X,Y
As you appear to be logging the X
and/or Y
values at each step, you may want to look into using the logging
module instead, creating a FileHandler
for the appropriate logger instead of passing output file names to myFunc
itself.由于您似乎在每一步都记录了
X
和/或Y
值,因此您可能需要考虑使用logging
模块,为适当的记录器创建FileHandler
,而不是将输出文件名传递给myFunc
本身。
import logging
# configuration of the logger objects is the responsibility
# of the *user* of the function, not the function itself.
def myFunc():
x_logger = logging.getLogger("myFunc.x_logger")
y_logger = logging.getLogger("myFunc.y_logger")
X,Y = 0,0
for i in range(1000):
X,Y = someCalculation(X, Y)
x_logger.info("%s", X)
y_logger.info("%s", Y)
return X,Y
Simpler: write to a "null device" file defined by your operating system to have no effect when written to.更简单:写入操作系统定义的“空设备”文件,写入时无效。
The standard library os
module defines a string constant devnull
which identifies the path to this file: '/dev/null'
on Mac and Linux, 'NUL'
on Windows (I suppose the latter is not actually a path).标准库
os
模块定义了一个字符串常量devnull
,它标识该文件的路径:Mac 和 Linux 上'/dev/null'
,Windows 上'NUL'
(我想后者实际上不是路径)。
import os
def myFunc(output1=os.devnull,output2=os.devnull):
# as before, with no special conditional logic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.