首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将输出重定向到python中的两个文件

将输出重定向到python中的两个文件
EN

Stack Overflow用户
提问于 2017-04-03 19:41:00
回答 1查看 1.5K关注 0票数 1

我正在写代码,我想用python重定向输出两个不同的文件。

一个用于日志目的,另一个用于fabric代码创建。

下面是将输出重定向到两个不同文件的代码:

代码语言:javascript
复制
import sys
print('###################################Creating storage commands         Variables##########################')
storage_file = open("Storage-output.txt", 'w')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
storage_file.close()
sys.stdout = sys.__stdout__  

# write fabric code
fabric_file = open("Fabric_code.py", 'w')
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
fabric_file.close()
sys.stdout = sys.__stdout__
storage_file = open("Storage-output.txt", 'a')
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
storage_file.close()
sys.stdout = sys.__stdout__  
# write fabric code
fabric_file = open("Fabric_code.py", 'a')
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
fabric_file.close()
sys.stdout = sys.__stdout__

在上面的代码中,创建了一个用于日志文件的Storage_file,用于存储该记录的文件和用于生成fabric代码的Fabric_code文件。

我的代码生成了1000个命令,我不想在python代码中一次又一次地打开和关闭两个不同的文件。

相反,有没有什么解决方案可以将打印输出重定向到两个直接文件,而无需打开和关闭

EN

回答 1

Stack Overflow用户

发布于 2017-04-03 19:46:11

您应该重构您的代码,在开始时打开文件一次,然后编写文件,最后关闭文件。从上面的示例中,我们可以执行以下操作:

代码语言:javascript
复制
import sys

# Open files
storage_file = open("Storage-output.txt", 'w')
fabric_file = open("Fabric_code.py", 'w')

# ===================
# Write Block
# ===================
print('###################################Creating storage commands         Variables##########################')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
sys.stdout = sys.__stdout__  

# write fabric code
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
sys.stdout = sys.__stdout__
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
sys.stdout = sys.__stdout__  
# write fabric code
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
sys.stdout = sys.__stdout__

# closing files
storage_file.close()
fabric_file.close()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43183699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档