当重定向sys.stdout时,numpy savetxt输出顺序混乱

1 投票
1 回答
1738 浏览
提问于 2025-04-18 02:34

我想用 numpy.savetxt 来写一个 numpy 数组,可以选择写到标准输出(stdout),或者通过重定向标准输出写到一个文件里。比如说(在 Python3 中)

import numpy as np
import sys

def output( a ):
    print( 'before np.savetxt' )
    np.savetxt( sys.stdout.buffer, a  )
    print( 'after np.savetxt' )

a = np.array( [ ( 1, 2, 3 ), ( 4, 5, 6 ) ] )

output( a )

with open( 'test', 'w' ) as file_out:
    sys.stdout = file_out
    output( a )

这样写的话(会输出到标准输出):

before np.savetxt
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
after np.savetxt

但是 'test' 文件里的内容顺序是错的:

> cat test
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
before np.savetxt
after np.savetxt

有没有办法让这些输出保持一致的顺序,还是说我应该用其他方法把 numpy.savetxt 和其他命令结合起来,写到同一个文件里呢?

1 个回答

2

在你的 output() 函数里面,你只能使用 savetxt 命令,并且需要传入 headerfooter 这两个参数:

def output( a ):
    header = 'before np.savetxt'
    footer = 'after np.savetxt'
    np.savetxt(sys.stdout.buffer, a, header=header, footer=footer)

正如 @DavidParks 提到的,对于 Python 2.7,应该使用 sys.stdout,而对于 Python 3.x,则应该使用 sys.stdout.buffer

撰写回答