2016-03-04 116 views
1

我正在尝试使用Python 3.4中的subprocess.Popen打开的管道中编写一个numpy数组数据。这里是Python - 将numpy数组数据写入用Popen打开的管道

import numpy 
import subprocess 

myArray = numpy.arange(10000).reshape([100,100]) 

fullCmd = "xpaset DS9Test array [xdim=100,bitpix=64,arch=littleendian,ydim=100]" 

mp = subprocess.Popen(
    fullCmd, 
    shell = True, 
    stdin = subprocess.PIPE, 
    stdout = subprocess.PIPE, 
    stderr = subprocess.STDOUT, 
    bufsize = 0 
) 

myArray.tofile(mp.stdin) 

不幸的是,我收到以下错误代码:

File "/Users/avigan/Work/HC-HR/FTS/test.py", line 25, in <module> 
    myArray.tofile(mp.stdin) 

OSError: first argument must be a string or open file 

但是,如果我这样做:

print(mp.stdin) 

<_io.FileIO name=71 mode='wb'> 

我解释这是一个迹象,表明文件描述符确实开放。

有人看到这里有什么不对吗?

+0

你必须看看编译的'numpy'代码,看看'tofile'如何测试这个参数。该测试可能不像文档所示的一般。 – hpaulj

回答

0

不完全是你要求的解决方案,但我有同样的问题想要将numpy数组重定向到PIPE,所以我可以将它重定向到feedgnuplot来构建直方图。

相反,我结束了使用临时文件如下:

import os 
import tempfile 

command = " | feedgnuplot --terminal 'dumb 160,40' --histogram 0 --with boxes --unset grid --exit" 
with tempfile.NamedTemporaryFile('w+t', suffix=".txt") as f: 
    np.savetxt(f, myArray, fmt='%.4f') 
    f.seek(0) 
    os.system("sudo more " + f.name + command) 

虽然你的使用要求可能是不同的,你仍然可以大概读回你自己的应用程序中的临时文件。

HTH

0

根据该文档,这应该是等同于tofile用于写入二进制数据:

mp.stdin.write(myArray.tobytes()) 

看看它是否工作。