Skip to content

Instantly share code, notes, and snippets.

@dan-zheng
Last active March 27, 2019 08:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dan-zheng/4e156113b8783ca26d9e3fae7baa8a27 to your computer and use it in GitHub Desktop.
Save dan-zheng/4e156113b8783ca26d9e3fae7baa8a27 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)

    Examples:

    export PYTHON_LIBRARY="~/anaconda2/lib/libpython2.7.so"
    export PYTHON_LIBRARY="~/anaconda3/lib/libpython3.7m.so"
    # Then, rerun Swift.
    
  • PYTHON_VERSION (forces a specific Python version)

  • PYTHON_LOADER_LOGGING (enables library loading debug log)

// 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
@johndpope
Copy link

problem with gist is - can't do PR. I solved my setup on osx with miniconda3

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

https://gist.github.com/johndpope/0933050234e5d5b7a17a4e6a6ab6c3d4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment