在Swift OS X应用程序中使用Python模块
如何在OSX应用程序中集成Python模块,以便从Swift调用Python?看起来大部分信息都过时了,我想确保我走上了正确的道路。答案取决于Python的复杂程度,以及您需要什么作为回报。在Swift中通过C接口使用Python的超级基本示例(请确保添加Python.framework): 对于更复杂的事情,它变得更复杂:在Swift OS X应用程序中使用Python模块,python,swift,macos,cocoa,Python,Swift,Macos,Cocoa,如何在OSX应用程序中集成Python模块,以便从Swift调用Python?看起来大部分信息都过时了,我想确保我走上了正确的道路。答案取决于Python的复杂程度,以及您需要什么作为回报。在Swift中通过C接口使用Python的超级基本示例(请确保添加Python.framework): 对于更复杂的事情,它变得更复杂: import Python Py_Initialize() // call urllib.urlopen('http://icanhazip.com').read()
import Python
Py_Initialize()
// call urllib.urlopen('http://icanhazip.com').read()
let module = PyImport_Import(PyString_FromString("urllib"))
let urlOpenFunc = PyObject_GetAttrString(module, "urlopen")
if urlOpenFunc != nil && PyCallable_Check(urlOpenFunc) == 1 {
let args = PyTuple_New(1)
PyTuple_SetItem(args, 0, PyString_FromString("http://icanhazip.com"))
let openCall = PyObject_CallObject(urlOpenFunc, args)
let readCall = PyObject_CallObject(PyObject_GetAttrString(openCall, "read"), nil)
if readCall != nil {
if let result = String.fromCString(PyString_AsString(readCall)) {
print("My IP is \(result)")
} else {
print("Failed")
}
}
}
如果您想在Python中进行一些严肃的工作,请确保Swift调用的接口超级简单,或者使用PyObjC。“看起来大部分信息都过时了”这一说法相当含糊。你到底找到了什么信息?为什么它过时了?您是否在现有答案上留言并要求更新?
import Python
Py_Initialize()
// call urllib.urlopen('http://icanhazip.com').read()
let module = PyImport_Import(PyString_FromString("urllib"))
let urlOpenFunc = PyObject_GetAttrString(module, "urlopen")
if urlOpenFunc != nil && PyCallable_Check(urlOpenFunc) == 1 {
let args = PyTuple_New(1)
PyTuple_SetItem(args, 0, PyString_FromString("http://icanhazip.com"))
let openCall = PyObject_CallObject(urlOpenFunc, args)
let readCall = PyObject_CallObject(PyObject_GetAttrString(openCall, "read"), nil)
if readCall != nil {
if let result = String.fromCString(PyString_AsString(readCall)) {
print("My IP is \(result)")
} else {
print("Failed")
}
}
}