正在使用Python shutil.move((方法,但需要将百万个文件从一个位置移动到另一个位置,我想重定向/静默shutil.move((的输出。
if os.path.exists(logs_path_archive):
for source_file in downloaded_files:
destination_file = source_file.replace(logs_path,logs_path_archive)
shutil.move(source_file,destination_file)
有什么建议吗?
在您指定的注释中,您使用的是Jupyter Notebooks。因此,您可以使用IPython/Jupyter中内置的几个选项来实现这一点。
如果移动步骤只是一个单元格,则在单元格的开头输入以下内容:
%%capture out_stream
shutil.move(<original_filename>,<new_file_name>)
但是,听起来移动步骤位于单元格中的许多其他步骤中,因此要仅隐藏移动,您可以使用with io.capture_output() as captured:
仅抑制with
块中内容的输出,如下所示:
from IPython.utils import io
with io.capture_output() as captured:
shutil.move(<original_filename>,<new_file_name>)
有关这两个方面的更多信息,请参阅此处的页面。%%capture
细胞魔法可能会在该链接将您发送到的位置之上。
如果你确实需要使用纯python,你可以使用with
语句和contextlib(如上下文管理器来处理输出(来重定向它,类似于上面的with io.capture_output() as captured
想法。在这里,我将其发送到_
当您不打算使用以后分配的对象时,通常会使用它。
import contextlib
with contextlib.redirect_stdout(_):
shutil.move(<original_filename>,<new_file_name>)