swift调用python3_在Swift OS X应用中使用Python模块

如何在OS X应用程序中集成Python模块,以便可以从Swift调用Python?似乎大多数信息都已过时,我想确保自己走的路正确.

解决方法:

答案取决于您的Python的复杂程度以及您的需求.通过Swift中的C接口仅使用Python的超级基本示例(请确保添加Python.framework):

import Python

Py_Initialize()

let a = PyInt_FromLong(1)

let b = PyInt_FromLong(2)

let c = PyNumber_Add(a, b)

let result = PyInt_AsLong(c)

print("Result is \(result)") // will print 'Result is 3'

对于更复杂的事情,它变得更加复杂:

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.

标签:swift,cocoa,python,macos

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值