简体   繁体   English

重定向sys.stdout时numpy savetxt混乱

[英]numpy savetxt out of order when redirecting sys.stdout

I would like to use numpy.savetxt to write a numpy array, with the option of writing either to stdout, or as part of a file (by redirecting stdout). 我想使用numpy.savetxt编写一个numpy数组,可以选择写入stdout或作为文件的一部分(通过重定向stdout)。 eg (in Python3) 例如(在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 )

This writes (to stdout): 这写到(到stdout):

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

but the 'test' file contains these entries out of order: 但是“测试”文件包含以下乱序输入:

> 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

Is it possible to have these outputs in consistent order, or should I use a different approach to combine numpy.savetxt with other commands to write to the same file? 是否可以使这些输出具有一致的顺序,还是应该使用其他方法将numpy.savetxt与其他命令组合以写入同一文件?

You can use inside your output() function only the savetxt command, passing the header and footer arguments: 您可以在output()函数内部仅使用savetxt命令,并传递headerfooter参数:

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

As well reminded by @DavidParks, it should be sys.stdout for Python 2.7 and sys.stdout.buffer for Python 3.x. 作为深受@DavidParks提醒,应sys.stdout为Python 2.7和sys.stdout.buffer为Python 3.x的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM