XCode/Swift and Python files - Want to embed a Python.py file in an XCode project

458 Views Asked by At

I want to create a Swift app that calls some embedded Python.py files using PythonKit.

In the docs and a sample file it says that I should use

let sys = Python.import("sys")
sys.path.append("/Users/mlboy/PythonTest/") // path to your Python file's directory.

This path is hardcoded and works when I do that with my own path..

But how can I reach those files relatively from the project when they are in the same project directory, so I don't need any hardcoded file.

I thought thats easy, so I did try.....

sys.path.append("./myPythonFiles/")
sys.path.append("./pythonTest/myPythonFiles/")

and some more. But none are working. After some googling I can't find a solution.

Suggestions?

Thank you.

1

There are 1 best solutions below

1
On

Took me a week of nights to come up with a solution for my similar needs. I am making a command line tool but I want to bundle the (unique) Python code with it. I also want to debug in Xcode, not deploy and run from command line disconnected from debugger most of the time. So my command line tool initializes a main struct (BpK) that initializes another struct PyRunner (first declared as static var bpPy: PyRunner! = nil) that does the Python invocations. My experimental strings are still included as this is WIP. I hope it will evolve into something more elegant.

public init() {
    let bundlePyURL = Bundle.main.url(forResource: "Python/.../sample", withExtension: "py") ??
        Bundle.module.url(forResource: "Python/.../sample", withExtension: "py")
    BpK.bpPy = PyRunner(libDirPath: undlePyURL!.deletingLastPathComponent().path)
}

then in the runner

`sys.path.append(libDirPath)
let example = Python.import(function)`