How do you call PyObjC code from Objective-C? [duplicate] - python

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Calling Python from Objective-C
I'm a long-time Python programmer and short-time Cocoa programmer. I'm just getting started with PyObjC and it's really amazing how easy it it is to get stuff done. That said, I wanted to try using pure ObjC for my controller with PyObjC models. I might be enjoy letting Python be Python and Objective-C be Objective-C. I figured it was worth a try, anyways.
Except I can't figure out or find anything about how to call Python from Objective-C, only the other way around. Can someone point me to any resources on this? (Maybe it's on the PyObjC site but I just don't know what I'm looking for?)
Edit: I'm most interested, at the basic level, in being able to call a Python module and get some native ObjC data types back.

There are several possible approaches. The most tempting is to use py2app to compile a loadable bundle from your python code from which you can access the principal class using NSBundle. Unfortunately, this use case hasn't gotten much love from the py2app developers, and I've found several bugs in 10.5 and 10.6, including a rather nasty memory leak when passing data from python back in to Objective-C. I wouldn't recommend using py2app at thist point.
The second approach is invert the embedding. Write a Python cocoa app and load your Objective-C code from a bundle at startup (even in main()). If you already have a large Objective-C app, this may take a bit of work. The only downside, that I'm ware of, is that you won't be able to use GC in your Objective-C code, but this is really a universal limitation in working with PyObjC.
Finally, you can instantiate a python interpreter in your Objective-C code to load your python code. This is obviously more involved, but may the best option if you already have a large Objective-C codebase into which you want to inject your python code. The main.m file from the Python-Cococa application template in Xcode is a good place to start to see this in action.

Whoops, guess I should've searched a bit more:
Calling Python from Objective-C

Related

Extending a C++ application with python

I have a legacy (but still internally maintained) application written in C++ which handles some hardware, interacts with databases, receives commands via serial line or socket... in short it does a non-trivial amount of work.
This application runs under Linux (ARM/Buildroot).
Now the need is to revamp the control interface adding a RESTful API.
I am exploring the possibility to do so via a Python extension.
Note I am a C++/java programmer and I'm not really proficient in Python, but I know the basics.
General idea would be:
Start a Python interpreter as a thread in the C++ application.
Use Flask/jinja2 (or just plain Bottle) to handle incoming RESTful requests.
Expose a few (perhaps just one) C++ class to Python.
Call from Python the appropriate C++ methods to perform the required actions.
I studied the official documentation (mainly pertaining plain C) and several alternatives, including:
Boost.Python (possibly too heavy for our limited hardware)
pybind11 (seems concerned only in extending Python, not embedding it).
http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I (deals only with embedding, without giving Python access to C++ classes).
Question are:
does this make any sense?
what is the least intrusive way (if any) to achieve this?
which lib/framework is advised to use?
is there some tutorial project along these lines?
I know the question is quite broad, but I hope to narrow it as soon as the first comments will point me in the right direction.
Can you do it the other way around - embed your C++ code in Python program? This way it would be more prepared for moving existing functionality Python like you said.
Python makes a lot of things easier (faster to develop, easier to maintain) - communication with databases, libraries (if hey have Python wrappers), process/thread management... Keep in C++ just the stuff that needs to be in C++, like dealing with hardware, C/C++-only libraries, CPU-heavy code.
Have a look at Cython for embedding C++ in Python. Cython is basically a compiler from Python-like language to a .c/.cpp file that "just" calls the Python C API, so it can be used from "normal" Python code, but can also call other C/C++ code.
Alternative: Implement an API in the C++ application and create a separate Python application that uses this API. By API I don't mean REST API, but something more low-level - RPC, ZeroMQ, plain sockets...

Python calling and using windows dll’s

I've to ask 1 question about python and dll functions which I'm a bit frustrated about. The question is - Can I load dll functions from windows using python? I heard of Ctype to do that, but I can’t find good tutorials for this. Is there another way to use dll files from windows to get extra functionality?
I want to call some dll to work with mouse events. I used pyautogui but it is not that useful for me. I wonder if python is good for windows applications? I know it runs on Windows however there are good dll function that can provide better functionality for windows then python original libraries. Well that’s my opinion what I think. Anyways, is it worth to work with dlls with python after all? Or I better study C# for that because I love python for simplicity and don’t want to move to C# yet.
Yes you can. The ctypes library is indeed what you need. The official doc is here https://docs.python.org/3/library/ctypes.html .
Loading DLLs pretty straightforward, but calling the functions inside can be a pain depending on the arguments types. Handling old C style error return codes is also cumbersome compared to the exception handling and general low overhead code style in Python.
99% of the time it is way easier and better to use an appropriate existing module that either implements what you need or wraps the appropriate DLL for you. For example search in PyPI which is the central repository of Python expternal modules. That's my advice.

Call from Objective-C into Python

bbum posted an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line?
Source here:
Calling Python From Objective-C
I have posted a full explanation of how to do this to my weblog as it is quite a bit longer than something I would post here.
The abstract summary remains the same: use an abstract class to provide the type information necessary to make the C compiler happy and the metadata necessary to make the bridge happy.
Unfortunately the story for using Python via PyObjC from within an Objective-C app is not very good at the moment. py2app which ships with PyObjC can compile loadable bundles (i.e. can be loaded via NSBundle), which seems like the best approach: define an NSObject subclass in python that implements a protocol (obtained via objc.protocolNamed) that you define in Objective-C, then compile this python file into a loadable bundle via py2app (which uses a standard setup.py). Unfortunately, py2app hasn't had much love, especially the plugin (loadable bundle) target, and a serious memory leak was introduced sometime around 10.5 such that any data passed from python to Objective-C from a py2app-compiled bundle leaks. Yuck.
PyObjC manipulates the Objective-C runtime in accordance with the ObjC-related code executed in Python, thus to be able to call python code from Objective-C, the general outline goes like
Write PyObjC wrapper around python code
Execute code declaring PyObjC wrapper to add these definitions to the ObjC runtime
Call PyObjC wrapper from Objective-C. Because it's declared at runtime, the symbols aren't available at compile time, so you'll have to use NSClassFromString et al. to instantiate the class. It's helpful to declare a #protocol with the appropriate methods so that the Objective-C compiler doesn't complain about missing methods.
If you have flexibility, the best option is to use the Cocoa-Python app templates (i.e. create a Python app), and then load your Objective-C code as a loadable bundle from within Python. This takes care of managing the Python interpreter for you.
Otherwise, with the code in main.m of the Cocoa-Python app template, you should be able to create a Python interpreter, execute your PyObjC code and then continue on. Obviously, the interpreter needs to be kept running so that your python code can execute, so you'll likely have to do this from a separate thread. As you can see this can get a little hairy. Better to go with the Python app, as described above.
Keep in mind that PyObjC is not guaranteed to play well with the Objective-C garbage collector, so all of these options require that your Objective-C code not use GC.
Google is your friend. Performing a search on the string "Cocoa Python" quickly turned up PyObjc.

Is it still Python 2.6 versus Python 3?

G'day,
I'm wanting to go back to Python after not using it for a while and I saw this question "Python Version for a Newbie" while wondering about getting back into Python 2.6 or Python 3.
Almost all of the questions' answers were along the lines that most of the code out there, libraries, legacy systems, etc., is 2.5 or 2.6 rather than 3 so start with 2.x now and then head towards 3 later on.
Given that the question and all answers date from early December 2008 I was wondering is this still the case?
Should someone who wants to get back into Python maybe start off with 2.6 and then head towards 3 later on?
Yes. Virtually all live production systems will use 2.5/2.6 for a long time yet. There's no point learning 3.0, only to have to downgrade it because your host doesn't support it.
95% of what you will learn in 2.5/2.6 is applicable to 3 anyway.
Depends on the amount of libraries you're going to use.
Raw Python, or all libs are available for Py3k - go for it without any doubts.
Python code distributed as standalone app (using PyInstaller), relying on some GUI lib, XML-lib, win32api etc - double check if all libs are available at least as betas for Py3k. Chances are still quite high that some older lib is not available for Python 3.x, and either you port it by yourself to new Python version, or you switch to some other lib or - stick to Python 2.6 for a while.
If you want to use only standard library then try Python 3.1. If you want to use others libraries/frameworks then they dictate the version to use. For example web2py framework will work best on 2.5.
I would say that Python 2.4 is the safest to learn, but the changes from 2.4->2.5->2.6 make some small progress towards Python 3.x, even if they may never make it (if I recall there will be some more steps?).
Python 3.1 can be used if you own a dedicated server and intend to build your own applications from the ground up. WSGI does support this, but I wouldn't recommend it.
As has already been said, I would learn the Python 2.5 or Python 2.6 style, but I would make a few changes.
Look at the Python 3 style regarding brackets.
e.g. The print function in 2.x has always been just
print "Hello World"
Where as in 3.x you need to enclose it
print("Hello World")
This is probably a good practice to pick up on, but things like Exceptions will cause issues if you use 3.x in 2.x. I know it's probably a bit confusing, but if you make sure you wrap your functions (additional brackets shouldn't really hurt most things) so that nothing is bare (bare like the first code snippet above), then it'll help with the transition.
The problem is, if you started with 2.4 or more it is better if you start from there, so you'll get on track faster, after some time when you feel comfortable with you code you can try 3.0 and find out what did they change and learn the new style.
I for once still code in 2.6 style and follow those guidelines, still haven't seen the changes in 3.0

Are there problems developing Django on Jython?

The background
I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.
The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python.
The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone.
Questions
Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)?
Decision
Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.
Django does work on Jython, although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified.
So as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer having all the Java libraries available or all of the Python libraries. At this point you can expect almost everything in the Python standard library to work with Jython, but there are still plenty of third-party packages which will not work, especially C extension modules. I'd personally recommend going with regular Python, but if you've got a ton of JVM experience and want to stick with what you know, then I can respect that.
As for finding Python hosting, this page might be helpful.
I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one.
It's true that very few cheap hostings offer Django preinstalled; but it's quite probable that that will change, given that it's the most similar environment to Google's app engine. (and most GAE projects can be made to run on Django)
I have recently started working on an open source desktop project in my spare time. So this may not apply. I came to the same the question. I decided that I should write as much of the code as possible in python (and Django) and target all the platforms CPython, Jython, and IronPython.
Then, I decided that I would write plugins that would interface with libraries on different implementations (for example, different GUI libraries).
Why? I decided early on that longevity of my code may depend on targeting not only CPython but also virtual machines. For today's purposes CPython is the way to go because of speed, but who knows about tomorrow. If you code is flexible enough, you may not have to decide on targeting one.
The downside to this approach is that you will have more code to create and maintain.
Django is supposed to be jython-compatible sinc version 1.0.
This tutorial is a bit outdated, but from there you can see there are no special issues.

Categories

Resources