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.array([[0,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,0,0]])
print(nextStep(seed))
But I'd like to be able to pass the initial array in command line. Any way I can do this ?
解决方案
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]]'