Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass list as argument to Python C module?

I found this nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument?

like image 757
c00kiemonster Avatar asked Jul 15 '10 07:07

c00kiemonster


People also ask

Can we pass list as argument in Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

What list in Python contains arguments passed to a script?

argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with sys argv python example below. With the len(sys.

How do you convert an argument to a string in Python?

Python has a built-in function str() which converts the passed argument into a string format. The str() function returns a string version of an object. The object can be int , char , or a string . If the object is not passed as an argument, then it returns an empty string.


1 Answers

From http://code.activestate.com/lists/python-list/31841/:

...
char * tok;         /* delimiter tokens for strtok */
int cols;           /* number of cols to parse, from the left */

int numLines;       /* how many lines we passed for parsing */
char * line;        /* pointer to the line as a string */
char * token;       /* token parsed by strtok */

PyObject * listObj; /* the list of strings */
PyObject * strObj;  /* one string in the list */

/* the O! parses for a Python object (listObj) checked
   to be of type PyList_Type */
if (! PyArg_ParseTuple( args, "O!is", &PyList_Type, &listObj, 
           &cols, &tok )) return NULL;

/* get the number of lines passed to us */
numLines = PyList_Size(listObj);

/* should raise an error here. */
if (numLines < 0)   return NULL; /* Not a list */

...

/* iterate over items of the list, grabbing strings, and parsing
   for numbers */
for (i=0; i<numLines; i++){

/* grab the string object from the next element of the list */
strObj = PyList_GetItem(listObj, i); /* Can't fail */

/* make it a string */
line = PyString_AsString( strObj );

/* now do the parsing */

See Parsing arguments and building values

like image 79
Marco Mariani Avatar answered Oct 17 '22 01:10

Marco Mariani