从用 Swift 编写的现有项目中调用 Python 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31927604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call Python code from an existing project written in Swift
提问by Shaun
I need a way to call Python code from Swift on an Apple platform. A library would be ideal. I've done a considerable amount of Google searching, and the closest material I found is for Objective-C.
我需要一种在 Apple 平台上从 Swift 调用 Python 代码的方法。图书馆将是理想的选择。我已经做了大量的谷歌搜索,我找到的最接近的材料是 Objective-C。
采纳答案by Shaun
If anyone is ever interested in calling python from swift, here is some helpful material I found:
如果有人对从 swift 调用 python 感兴趣,这里有一些我发现的有用材料:
- U the python framework - https://developer.apple.com/library/ios/technotes/tn2328/_index.html
- PyObjC (a little more challenging) -
- Cobbal - https://github.com/cobbal/python-for-iphone
- Python docs (you would need to make C-Swift bridge)
- U python 框架 - https://developer.apple.com/library/ios/technotes/tn2328/_index.html
- PyObjC(更具挑战性)-
- Cobbal - https://github.com/cobbal/python-for-iphone
- Python 文档(您需要制作 C-Swift 桥接器)
Most of it is for Objective-c, but if you need to use swift you can easily just create an ObjC-Swift bridge (super-super easy) - Lookup the apple docs
大部分是针对 Objective-c 的,但是如果你需要使用 swift,你可以轻松地创建一个 ObjC-Swift 桥(超级超级简单) - 查找苹果文档
回答by hauntsaninja
I found this excellent and up to date gist that walks you through a complete solution: https://github.com/ndevenish/Site-ndevenish/blob/master/_posts/2017-04-11-using-python-with-swift-3.markdown
我发现了这个优秀且最新的要点,可以引导您完成一个完整的解决方案:https: //github.com/ndevenish/Site-ndevenish/blob/master/_posts/2017-04-11-using-python-with-swift -3.降价
If you can get away with just using NSTask to launch a Python process, that's a pretty good option too.
如果您可以仅使用 NSTask 来启动 Python 进程,那也是一个不错的选择。
回答by Max Rogers
In Swift 4.2 there was an approved feature to allow dynamic languages to be ported directly into swift
在 Swift 4.2 中,有一项经过批准的功能允许将动态语言直接移植到 swift
https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md
https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md
Will look similar to:
将类似于:
// import pickle
let pickle = Python.import("pickle")
// file = open(filename)
let file = Python.open(filename)
// blob = file.read()
let blob = file.read()
// result = pickle.loads(blob)
let result = pickle.loads(blob)
回答by Alex Shoshiashvili
In swift 5 you can try PythonKitframework.
在 swift 5 中你可以尝试PythonKit框架。
Here's example of the usage:
以下是用法示例:
import PythonKit
let sys = try Python.import("sys")
print("Python \(sys.version_info.major).\(sys.version_info.minor)")
print("Python Version: \(sys.version)")
print("Python Encoding: \(sys.getdefaultencoding().upper())")