简体   繁体   English

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

[英]How to assign python array to gnuplot array?

I have the following code where I'm trying to assign a python array A to gnuplot array B but, I'm not able to iterate over the python array.我有以下代码,我试图将 python 数组 A 分配给 gnuplot 数组 B,但是我无法遍历 python 数组。 How do I do this?我该怎么做呢?

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
"""
)

The above program prints: [3,3,3].上面的程序打印:[3,3,3]。 I'm expecting to print [1,2,3].我期待打印 [1,2,3]。 (Essentially I've to access the i from the gnuplot in python) (基本上我必须从 python 中的 gnuplot 访问 i )

Gnuplot version 5.2 patchlevel 2 Gnuplot 版本 5.2 补丁级别 2

Python version 3.6.9 Python 版本 3.6.9

This will do the trick这会成功的

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
"""
)

The issue is that the data lives in two different environments, no there is not much gnuplot can do to get the data from python, to communicate them you use proc.communicate that sends the message to the gnuplot but also waits until the process finishes, which closes the pipe with gnuplot and doesn't allow us to send all the data we want, using proc.stdin.write fixes that.问题是数据存在于两个不同的环境中,没有太多 gnuplot 可以做的事情是从 python 获取数据,您可以使用proc.communicate将消息发送到 gnuplot 但也要等到进程完成才能与它们通信,它使用 gnuplot 关闭 pipe 并且不允许我们发送我们想要的所有数据,使用proc.stdin.write修复了这个问题。

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

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