如何在fileinput循环中将stdout重定向到仅控制台

时间:2014-11-13 19:30:29

标签: python python-2.7 stdout

目前我有这段代码用于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'))

我需要将此信息仅输出到控制台,而不是输入HISTORY文件。

2 个答案:

答案 0 :(得分:1)

此代码创建输入文件的临时副本,然后扫描并重写原始文件。它在处理文件期间处理错误,以便在重写期间原始数据不会丢失。它演示了如何偶尔将一些数据写入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()

答案 1 :(得分:0)

如果您只想将信息发送到控制台,那么您只需使用print吗?