Embedding Python in a Cocoa Application

November 4th, 2008 · 4 Comments · Tutorials

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!

Tags: ····

4 responses 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).


  • 2 nickyo2  Apr 4, 2012 at 6:59 am

    The code is not working it is giving an error which says The run destination My Mac 64 -bit is not valid for running the scheme “Python Console”

  • 3 Hamish M  May 5, 2012 at 10:52 pm

    @nickyo2 — Go to the projects Build Settings and select a base SDK in the Python Console column.

    Thanks for this Tobias!

  • 4 Julian Merghart  Mar 27, 2014 at 9:41 am

    Wow. This is badass. This pretty much means I can run any Python script I find inside of Xcode 4. Question… How do I link a python class to a Cocoa Button or Binding?

© 2013 Tobis Lensing. All rights reserved. Powered by Wordpress — based upon Cutline by Chris Pearson. This page reflects the personal opinion of the author and is in no way linked to institutions the author is working or has worked for. For more information, see the disclaimer and Privacy Policy.