2

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. 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]. I'm expecting to print [1,2,3]. (Essentially I've to access the i from the gnuplot in python)

Gnuplot version 5.2 patchlevel 2

Python version 3.6.9

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.