python-3.xnumpymatplotlib

How to pass a list of 2d arguments to Python?


The use case is I have a list of x,y coordinates that I display in a matplotlib graph. I hard coded the values as below to get it to work.

The code I was using is:

import matplotlib.pyplot as plt
import numpy as np
import argparse  #added in later

data = np.array([[1,4], [2,2], [4,7], [6,3]])
x,y = data.T
print (data)

Which works, so I tried to add in argparse in order to make it dynamic with n(arguments) and take out the hard coded values:

parser = argparse.ArgumentParser()
args = parser.parse_args()

after passing in arguments in many variations of the following:

python multi_point.py ([[1,4], [2,2], [4,7], [6,3]])

I keep getting errors relating to this structure as a "namespace" and not an iterable?

However, I don't know if it's the wrong library for this or my terminal syntax is wrong or something else? Btw, I'm using VSCode as my IDE and running it on a terminal.

Any ideas as to what I'm doing wrong?


Solution

  • You can use ast to parse string literals to your python program :

    import matplotlib.pyplot as plt
    import numpy as np
    import argparse
    import ast  # added to parse the string representation of the list
    
    # Define the command-line argument
    parser = argparse.ArgumentParser()
    parser.add_argument('data', type=str, help='List of lists representing data points')
    args = parser.parse_args()
    
    # Parse the string representation of the list into a Python list
    data = ast.literal_eval(args.data)
    data = np.array(data)
    
    x, y = data.T
    print(data)
    
    

    You will still need to wrap your argument in doublequotes because of the spaces :

    python test.py "[[1,4], [2,2], [4,7], [6,3]]"
    

    Which should output :

    [[1 4]
     [2 2]
     [4 7]
     [6 3]]