Skip to content Skip to sidebar Skip to footer

Can I Pass A Matrix As Command Line Input In Python With Numpy?

I'm working on a simple program that gives me the next step of Conway's game of life, using numpy. Right now, all I can do is alter the ones and zeros in the program :- seed = np.

Solution 1:

What you want is basically to convert text into structured data (numpy array here). Because doing so manually (like splitting strings or using eval) is fraught with bugs and security vulnerabilities, I recommend using a library that does the parsing for you.

Here I think json is the most natural format. Example usage

import json
import numpy
import sys

data = numpy.array(json.loads(sys.argv[1]))
# do you calculation

Now you can run on the command line

python myscript.py '[[0,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,0,0]]'

Solution 2:

eval can do that :

python myprogram.py "[[0,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,0,0]]"

python code :

import sys

......

seed = np.array(eval(sys.argv[1]))

Solution 3:

If you want to write

$ python life.py 0101010,0101010,0101010

then you need the argv vector from the sys module, that contains all the elements in the command line, and then a simple list comprehension to split the 1st argument on commas, hence rows of your matrix (note that these rows are strings) and then build a sub-list converting each character in a row

from sys import argv
...
life = np.array([[int(c) for c in r] for r in argv[1].split(',')])

To show in detail the procedure, using an auxiliary variable in place of argv[1]

In [46]: m = '0101010,0101010,0101010'

In [47]: [r for r in m.split(',')]
Out[47]: ['0101010', '0101010', '0101010']

In [48]: [[c for c in r] for r in m.split(',')]
Out[48]: 
[['0', '1', '0', '1', '0', '1', '0'],
 ['0', '1', '0', '1', '0', '1', '0'],
 ['0', '1', '0', '1', '0', '1', '0']]

In [49]: [[int(c) for c in r] for r in m.split(',')]
Out[49]: [[0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0]]

In [50]: np.array([[int(c) for c in r] for r in m.split(',')])
Out[50]: 
array([[0, 1, 0, 1, 0, 1, 0],
       [0, 1, 0, 1, 0, 1, 0],
       [0, 1, 0, 1, 0, 1, 0]])

In [51]: 

Post a Comment for "Can I Pass A Matrix As Command Line Input In Python With Numpy?"