python - How to redirect stdout to only the console when within fileinput loop -



python - How to redirect stdout to only the console when within fileinput loop -

currently have piece of code python 2.7:

h = 0 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)

what having problem next line:

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

i need info outputted console , not history file.

this code creates temporary re-create of input file, scans , rewrites original file. handles errors during processing file original info isn't lost during re-write. demonstrates how write info stdout , other info original file.

the temporary file creation taken this answer.

import fileinput import os, shutil, tempfile # create re-create of source file scheme specified # temporary directory. set in original # folder, if 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) homecoming temp_path # create temporary re-create of input file temp = create_temp_copy('history.txt') # open input file writing dst = open('history.txt','w+') line in fileinput.input(temp): # added try/catch handle errors during processing. # if isn't present, exceptions raised # during processing cause unrecoverable loss of # history file try: # sort of replacement if line.startswith('e'): line = line.strip() + '@\n' # notice newline here # occasional status updates stdout if '0' in line: print 'info:',line.strip() # notice removal of newline except: # when problem occurs, output message print 'error processing input file' finally: # re-write original input file # if there exceptions dst.write(line) # deletes temporary file os.remove(temp) # close original file dst.close()

python python-2.7 stdout

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -