首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在文件输入循环中将stdout重定向到控制台

如何在文件输入循环中将stdout重定向到控制台
EN

Stack Overflow用户
提问于 2014-11-13 19:30:29
回答 2查看 759关注 0票数 2

目前,我有一段用于python 2.7的代码:

代码语言:javascript
运行
复制
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)

我遇到困难的是以下几句话:

代码语言:javascript
运行
复制
sys.stdout.write(('\r%s%% ') % format(((os.stat('HISTORY').st_size / os.stat('HISTORY.bak').st_size)*100),'.1f'))

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-13 20:28:29

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

临时文件创建是从this SO answer中提取的。

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2014-11-13 19:35:36

如果您只想将信息转到控制台,那么可以直接使用print吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26916864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档