如何将 python 数组分配给 gnuplot 数组?

How to assign python array to gnuplot array?

我有以下代码,我试图将 python 数组 A 分配给 gnuplot 数组 B,但是我无法遍历 python 数组。我该怎么做?

import subprocess

proc = subprocess.Popen(['gnuplot','-p'], 
                        shell=True,
                        stdin=subprocess.PIPE,
                        encoding='utf8'
                        )

A = [1, 2, 3]
proc.communicate(
f"""
array B[3]
do for [i=1:3] {{ B[i] = {A[2]} }}
print B
"""
)

以上程序打印:[3,3,3]。我期待打印 [1,2,3]。 (基本上我必须从 python 中的 gnuplot 访问 i)

Gnuplot 版本 5.2 补丁级别 2

Python 版本 3.6.9

这样就可以了

import subprocess

proc = subprocess.Popen(['gnuplot','-p'], 
                        shell=True,
                        stdin=subprocess.PIPE,
                        encoding='utf8'
                        )

A = [1, 2, 3]

# create the array
proc.stdin.write( 'array B[{}]; print B;'.format( len(A) ) )

# send the data piece by piece
for i,x in enumerate(A):
    proc.stdin.write( 'B[{}] = {};'.format( i+1, x ) )

# print the array in gnuplot and finish the process
proc.communicate(
f"""
print B
"""
)

问题是数据存在于两个不同的环境中,不,gnuplot 无法从 python 获取数据,要与它们通信,您可以使用发送消息的 proc.communicate到 gnuplot 但也会等到进程完成,这会关闭 gnuplot 的管道并且不允许我们发送我们想要的所有数据,使用 proc.stdin.write 修复了这个问题。