我正在写代码,我想用python重定向输出两个不同的文件。
一个用于日志目的,另一个用于fabric代码创建。
下面是将输出重定向到两个不同文件的代码:
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代码中一次又一次地打开和关闭两个不同的文件。
相反,有没有什么解决方案可以将打印输出重定向到两个直接文件,而无需打开和关闭
发布于 2017-04-03 19:46:11
您应该重构您的代码,在开始时打开文件一次,然后编写文件,最后关闭文件。从上面的示例中,我们可以执行以下操作:
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()https://stackoverflow.com/questions/43183699
复制相似问题