我有以下代码,我试图将 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/