簡體   English   中英

Python-將numpy數組數據寫入使用Popen打開的管道

[英]Python - Writing numpy array data to a pipe opened with Popen

我正在嘗試將numpy數組數據寫入在Python 3.4中使用subprocess.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'>

我將其解釋為文件描述符確實打開的跡象。

有人看到這里有什么問題嗎?

並不是您所要求的解決方案,但是我有一個同樣的問題,想將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

根據文檔,這應該等效於tofile用於寫入二進制數據:

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

看看它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM