Archive

Posts Tagged ‘embedded python’

Call Python from C

July 1, 2013 1 comment

Problem
You want to embed Python code inside a C program.

Solution
See this: http://docs.python.org/2/extending/embedding.html.

Example:

#include "Python.h"

int main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

Compilation:

gcc -I/usr/include/python2.7 cool.c -lpython2.7
# or:
clang -I/usr/include/python2.7 -lpython2.7 cool.c

Sample output:

Today is Mon Jul  1 00:53:10 2013

For more details, please refer to this page.

Update (20140216)
I tried this example today and clang dropped me this error:

/usr/include/limits.h:124:16: fatal error: 'limits.h' file not found

I have Clang 3.2 on my machine and it’s a known bug. There is a workaround:

$ cd /usr/lib/clang/3.2/
$ sudo ln -s /usr/lib/llvm-3.2/lib/clang/3.2/include

Write Python inside Bash

November 24, 2012 2 comments

Problem
You want to embed Python code inside a Bash script.

Solution
Here is a possible solution:

#!/usr/bin/bash

# name.sh

# Example:
# Write a bash script that has one parameter: your name.
# It prints every second character of your name.

TFILE="`basename $0`.$$.py"

cat <<END >$TFILE
#!/usr/bin/env python

import re
import sys

bash_name = re.sub(r'\.\d+\.py', '', sys.argv[0])

def process(s):
    print s[::2]

def main():
    if len(sys.argv) > 1:
        process(sys.argv[1])
    else:
        print "Usage: {0} <parameter>".format(bash_name)

if __name__ == "__main__":
    main()
END

chmod u+x $TFILE
./$TFILE "$@"
/bin/rm $TFILE

Usage:

./name.sh Your_Name
Yu_ae    # output
Categories: fun, python Tags: ,