2017-04-03 69 views
0

我写代码,我想重定向在python输出重定向到两个文件在python

一个日志目的输出两个不同的文件,另一个用于织物的代码创建。

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

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_code文件genarate面料代码。

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

相反的,这是没有任何解决方案,我可以打印输出重定向到两次直接文件,而无需打开和关闭

+0

asteroid4u:下面提到的解决方案不适合你吗? –

回答

0

你应该重构你的代码在年初曾经打开的文件,然后写你的文件,并关闭文件到最后。从上面的例子我们可以做到以下几点:

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()