You can run Python scripts from Swift using PythonKit. This allows you to develop Mac apps that run Python scripts. (Does not work on iOS)
Open your Xcode project. Go to "file-> Swift Packages-> Add Package Dependency". Copy and paste the Package Dependency URL from the PythonKit GitHub repository (https://github.com/pvieito/PythonKit).
Select Branch: master.
Create a Python file. For example, I wrote "example.py". ↓
example.py
def hello():
print("Hello PythonKit")
}
Make the following settings in the Xcode project settings "TARGETS → Signing & Capabilities". · Access files on your Mac instead of the app sandbox -Disable library validation
Call the Python file from the view controller.
ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
let sys = Python.import("sys")
sys.path.append("/Users/mlboy/PythonTest/") // example.Path to the directory where py is
let example = Python.import("example") //Import python file
example.hello() //Call a Python function
}
Check the Xcode console. The Python file will be executed and the "Hello Python Kit" will be printed.
Recommended Posts