Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Python code from an existing project written in Swift

Tags:

python

swift

I need a way to call Python code from Swift on an Apple platform. A library would be ideal. I've done a considerable amount of Google searching, and the closest material I found is for Objective-C.

like image 970
Shaun Avatar asked Aug 10 '15 19:08

Shaun


People also ask

Can I call Python from swift?

Yes, you can run python code from swift by using the PythonKit, a framework based on the Python module from the Swift for TensorFlow project. It's important to note that Python is not available on iOS.

Can you run Python code on iOS?

iOS does not have Python pre-installed, so you'll have to embed a copy of Python within your app. Additionally, iOS apps can't run arbitrary secondary processes, so you'll have to run the Python interpreter inside your app's process. That's quite possible, but it involves a good understanding of the Python runtime.


1 Answers

In swift 5 you can try PythonKit framework.

Here's example of the usage:

import PythonKit  let sys = try Python.import("sys")  print("Python \(sys.version_info.major).\(sys.version_info.minor)") print("Python Version: \(sys.version)") print("Python Encoding: \(sys.getdefaultencoding().upper())") 
like image 125
Alex Shoshiashvili Avatar answered Sep 18 '22 18:09

Alex Shoshiashvili