PythonKit Documentation

repository·main·Indexed 24 days ago

https://github.com/pvieito/pythonkit

A Swift framework that enables interaction with Python, allowing developers to import and use Python modules directly within Swift code via Python.import(). Includes configuration options for Python versions and library paths using environment variables.

Tokens
466
Snippets
2
Records
4
Agent score
31%

What's inside PythonKit

  1. Install PythonKit via Swift Package Manager

    main

    To use PythonKit in your Swift project, add it as a dependency in your Package.swift manifest using the following URL and branch:

    .package(url: "https://github.com/pvieito/PythonKit.git", branch: "main"),
  2. Troubleshoot Python library loading on macOS with Hardened Runtime

    main

    If you are targeting macOS with the Hardened Runtime enabled, the Library Validation mechanism may prevent PythonKit from loading the Python framework if it is not signed by Apple or the same developer as your main process.

    To resolve this, ensure you are properly signing and embedding the Python framework you intend to load, or consider disabling library validation if appropriate for your security model.

  3. Use PythonKit to interact with Python from Swift

    main

    PythonKit allows you to import Python modules directly into Swift using Python.import("module_name"). Once imported, you can access Python attributes, methods, and properties as if they were native Swift objects.

    import PythonKit
    
    let sys = Python.import("sys")
    
    print("Python \(sys.version_info.major).\(sys.version_info.minor)")
    print("Python Version: \(sys.version)")
    print("Python Encoding: \(sys.getdefaultencoding().upper())")
  4. Configure Python version and library path with environment variables

    main

    PythonKit attempts to find the most modern Python version available on your system at runtime. You can override this behavior using the following environment variables:

    • PYTHON_VERSION: Force a specific Python version (e.g., 3 or 2.7).
    • PYTHON_LIBRARY: Specify a specific Python library name or absolute path to the library file.

    To debug library loading issues, set PYTHON_LOADER_LOGGING=TRUE to see the search paths attempted by PythonKit.