Using PythonKit in Xcode Playground and project

Hi, I'm trying using PythonKit in my Xcode project and Playground for data science with Swift instead of Jupyter Notebook.

I have some questions about PythonKit.

1. Specifying python path in my Xcode project and Playground

In my Xcode Playground, the version of Python is 3.9, but I'm using conda to install python 3.7 in my shell

# In my zsh shell
$ python --version
$ which python
python: aliased to /opt/miniconda3/bin/python3
// In Playground.swift
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())")

// Python 3.9
// Python Version: 3.9.2 (default, Feb 24 2021, 13:26:09) 
// [Clang 12.0.0 (clang-1200.0.32.29)]
// Python Encoding: UTF-8

My questions:

  • Is that possible to specify python path in my Playground and Xcode project?
  • How do I ship my Swift App with Python and Python modules? It might be:
    • a macOS app
    • an iOS app
    • a pure swift executable running on Linux (maybe within a docker container).

2. How to draw matplotlib's plots in the Playground and macOS Apps

Is that possible to call matplotlib API and draw plots with Swift in a Xcode Playground or a macOS app? Is there any sample code or project to do that?

3. Data Science in Swift

Is there any recommended Swift package could be replaced/compatible with numpy, pandas, matplotlib, etc. when using PythonKit?

Any help would be appreciated.

I only know how to resolve your first question.

You can use PythonLibrary.useVersion to change the Python version. As PythonLibrary. enforceNonLoadedPythonLibrary indicates, you must call PythonKit.useVersion before loading any Python libraries.

It seems to search system python for use. How could I specify python installed by conda?

Hi @xareelee, quite interesting to see more data science interest in Swift! I encountered the same issue for some project I'm working on where I use PythonKit with Swift and Python is installed via Conda. Here's an internal note for the fix that I have been using so far in Xcode:

Note: add PYTHON_LIBRARY ENV variable to point to Conda Python in XCode for running/testing (From "Edit Scheme..."). Example /opt/miniconda3/envs/<yourenv>/lib/libpython3.8.dylib

1 Like

Thanks for reply.

To make this work, you also need to set "App Sandbox" (key: ) to "NO" in the .entitlement file while development, and this only works for the project, not for Xcode Playground.

  1. In my playground within the same project, the python version is still not my conda's Python. I still wonder how to achieve this in Xcode's Playground.

  2. Furthermore, how to archive this Xcode project into .app with the specific Python version and associated libs?

Terms of Service

Privacy Policy

Cookie Policy