I stumbled upon Ragestorm.net’s great tutorial on Python embedding when I was trying to embed Python in a Cocoa application and redirect standard output / standard error to an NSTextView. Ragestorm’s tutorial is not particularly about Cocoa / Objective-C, but does though solve the problem. Stdout / stderr is simply redirected using a fragment of Python code, which is injected directly after the Python runtime is loaded. It makes use of a couple of C-functions provided by the host application, which connect the Python output to the Cocoa-based NSTextView.
I have uploaded the Python Console Sample Xcode project containing all the code. I think it’s pretty self-explanatory. Have fun!





1 response so far ↓
1 Ivan Vučica Jan 26, 2012 at 1:37 pm
Excellent, excellent example!
However, Py_SetProgramName() is used incorrectly; it should be the path to the executable of the running program, the value of argv[0] as passed to main(). Alternatively, you could hack it and pass /usr/bin/python. Passing “Python Console”, however, doesn’t seem like a good idea, judging by the documentation for this function (which claims Py_GetPath() and some other functions use this to find run-time libraries relative to the interpreter executable).
Leave a Comment