Skip to main content
 首页 » 编程设计

python之在文件输入循环中如何将标准输出重定向到控制台

2025年05月04日9webabcd

目前我有这段 python 2.7 的代码:

h = 0 
for line in fileinput.input('HISTORY',inplace=1): 
    if line[0:2] == x: 
            h = h + 1 
            if h in AU: 
                    line = line.replace(x,'AU') 
    if 'timestep' in line: 
        h = 0 
        sys.stdout.write(('\r%s%% ') % format(((os.stat('HISTORY').st_size / os.stat('HISTORY.bak').st_size)*100),'.1f')) 
    sys.stdout.write(line) 

我遇到的问题是以下行:

sys.stdout.write(('\r%s%% ') % format(((os.stat('HISTORY').st_size / os.stat('HISTORY.bak').st_size)*100),'.1f')) 

我只需要将此信息输出到控制台,而不是历史文件。

请您参考如下方法:

此代码创建输入文件的临时副本,然后扫描它并重写原始文件。它在处理文件期间处理错误,以便原始数据在重写期间不会丢失。它演示了如何偶尔将一些数据写入 stdout 并将其他数据写回原始文件。

临时文件创建取自 this SO answer .

import fileinput 
import os, shutil, tempfile 
 
# create a copy of the source file into a system specified 
# temporary directory. You could just put this in the original 
# folder, if you wanted 
def create_temp_copy(src_filename): 
    temp_dir = tempfile.gettempdir() 
    temp_path = os.path.join(temp_dir, 'temp-history.txt') 
    shutil.copy2(src_filename,temp_path) 
    return temp_path 
 
# create a temporary copy of the input file 
temp = create_temp_copy('HISTORY.txt') 
 
# open up the input file for writing 
dst = open('HISTORY.txt','w+') 
 
for line in fileinput.input(temp): 
 
    # Added a try/catch to handle errors during processing. 
    # If this isn't present, any exceptions that are raised 
    # during processing could cause unrecoverable loss of 
    # the HISTORY file 
    try: 
        # some sort of replacement  
        if line.startswith('e'): 
            line = line.strip() + '@\n' # notice the newline here 
 
        # occasional status updates to stdout 
        if '0' in line: 
            print 'info:',line.strip() # notice the removal of the newline 
    except: 
        # when a problem occurs, just output a message 
        print 'Error processing input file' 
 
    finally: 
        # re-write the original input file 
        # even if there are exceptions 
        dst.write(line) 
 
# deletes the temporary file 
os.remove(temp) 
 
# close the original file 
dst.close()