Skip to content

Instantly share code, notes, and snippets.

@johndpope
Forked from dan-zheng/README.md
Last active March 27, 2019 08:19
Show Gist options
  • Save johndpope/0933050234e5d5b7a17a4e6a6ab6c3d4 to your computer and use it in GitHub Desktop.
Save johndpope/0933050234e5d5b7a17a4e6a6ab6c3d4 to your computer and use it in GitHub Desktop.
Python interoperability in Swift

Python interoperability

Check out this tutorial demonstrating Python interoperability in Swift.

Python library version details

This function is intended to set the Python version before any references to the global PythonInterface called Python - it cannot be used to switch Python versions dynamically.

This could be better designed/documented so that people don't get the impression that switching Python versions is possible.

Special environment variables (defined here)

  • PYTHON_LIBRARY (sets the Python library path, useful for setting a specific Python version)

    Anaconda:

    export PYTHON_LIBRARY="~/anaconda2/lib/libpython2.7.so"
    export PYTHON_LIBRARY="~/anaconda3/lib/libpython3.7m.so"
    
    

    Miniconda (osx):

    export PYTHON_LIBRARY="~/miniconda3/lib/libpython3.7m.dylib"
    export PYTHON_LIBRARY="~/miniconda2/lib/libpython2.7.dylib"
    

Then, rerun Swift.

// First, run `wget https://via.placeholder.com/150.png` and `pip3 install pillow`.
import Python
PythonLibrary.useVersion(3)
print(Python.version)
// 3.7.2 (default, Feb 12 2019, 08:16:38)
// [Clang 10.0.0 (clang-1000.11.45.5)]
let PIL_Image = Python.import("PIL.Image")
let image = PIL_Image.open("150.png")
print(image.format, image.size, image.mode)
// PNG (150, 150) P
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment