gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:27 25 4
gpt4 key购买 nike

目前我有这段 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()

关于python - 在文件输入循环中如何将标准输出重定向到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com