Calling Python Scripts from Swift by PythonKit.

MLBoy
2 min readJun 18, 2020

--

You can use python scripts on Swift with PythonKit.
With it, for example, you can develop a mac app what can call Python scripts.

(It’s not work on iOS)

1, Open your Xcode project. And, “file→Swift Packages→Add Package Dependency”, then enter package dependency URL from https://github.com/pvieito/PythonKit

2,Choose package options.

3,Write your python file.For example, I wrote “example.py”. ↓

#example.pydef hello():
print("Hello PythonKit")

4,Set up your Xcode project to access files on your Mac instead of the app sandbox and disable library validation. “TARGETS→Signing & Capabilities”

5,Now Call your Python file from your ViewController.

override func viewDidLoad() {super.viewDidLoad()let sys = Python.import("sys")sys.path.append("/Users/mlboy/PythonTest/") // path to your Python file's directory.let example = Python.import("example") // import your Python file.example.hello() // call your Python function.}

Check your Xcode console. Python file works.

--

--