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

标签 python gnuplot f-string

我有以下代码,我试图将 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 修复了这个问题。

关于python - 如何将 python 数组分配给 gnuplot 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445452/

相关文章:

python - 使用 Django 和 MySQL 存储和查找大型 DNA 微阵列结果

macos - 无法在 osx yosemite 上进行枪战。 undefined symbol

gnuplot - 让 GNUPLOT 从 shell 中保存一个图

Gnuplot 直方图显示 Y 中字符串出现的次数

python - 为什么这个使用 Python f-string 的打印语句输出双括号?

python - 将使用 lambda 的字符串连接转换为 f 字符串

python - 符合 PEP8 的长 f 字符串拆分

python - 使用 Python 脚本从 Outlook 2013 下载附件

python - 更改自动插入到 tkinter 小部件中的文本的颜色

python - 使用 DataFrame 对象时,plot_2d_separator 会提示(引发 AttributeError)