简体   繁体   English

如何在使用swift的同时运行/调用python脚本?

[英]How can I run/call a python script while using swift?

I am trying to make an iOS app that will calculate pi to a set about of decimal places based on what the user wants. 我正在尝试制作一个iOS应用程序,该应用程序将根据用户的需要将pi计算为小数点后一组。 I currently have a python script that will take in an integer value from the user and then use that in the calculation of Pi. 我目前有一个python脚本,它将从用户那里获取一个整数值,然后将其用于Pi的计算中。 I also have a swift/Xcode project that will only allow a user to input an integer value. 我也有一个swift / Xcode项目,该项目仅允许用户输入一个整数值。 So I am wondering if there is a way for me to pass this value that the user enters from a textbox in my swift project to then give that to the python code, run it, and then output the result? 所以我想知道是否有一种方法可以传递用户从我的swift项目中的文本框中输入的值,然后将该值提供给python代码,运行它,然后输出结果? In my python code, I am using "timer" to be able to calculate the time it takes to calculate pi to the set digits that was requested. 在我的python代码中,我正在使用“计时器”来计算将pi计算为所请求的设置数字所花费的时间。 So I would only need to be able to display this result. 因此,我只需要能够显示此结果。

I have thought about rewriting the python script into swift, but I am unsure of how to do that. 我曾考虑过将python脚本重写为swift,但是我不确定如何做到这一点。 This is the definition I am using in my python script to calculate pi: 这是我在python脚本中用于计算pi的定义:

def pi():
decimal.getcontext().prec += 2
three = decimal.Decimal(3)
first, second, third, forth, fifth, sixth, numb = 0, three, 1, 0, 0, 24, 3 
while numb != first:
    first = numb
    third, forth = third + forth, forth + 8
    fifth, sixth = fifth + sixth, sixth + 32
    second = (second * third) / fifth
    numb += second
decimal.getcontext().prec -= 2
return +numb

But I was unsure of how to rewrite this into swift language, so I figured getting swift to pass the precision value into python would be easier. 但是我不确定如何将其重写为快速语言,因此我认为快速将精度值传递给python会更容易。

You definitely can run Python code in Swift since Python is designed to be embedded and has a C interface API. 您肯定可以在Swift中运行Python代码,因为Python被设计为嵌入式的并且具有C接口API。 Check how Swift for TensorFlow uses Python interoperability (although I couldn't find a quick way to only use that module and not the whole TensorFlow). 检查Swift for TensorFlow如何使用Python互操作性(尽管我找不到仅使用该模块而不是整个TensorFlow的快速方法)。 You can also check PythonKit out. 您也可以签出PythonKit

However , I don't think rewriting that script would be too difficult, and it might be better to avoid more libraries and dependencies in your project. 但是 ,我认为重写该脚本不会太困难,最好避免在项目中使用更多的库和依赖项。

Edit: As Joakim Danielson pointed out, you'll need the Python runtime, and it doesn't seem to be available in iOS, so you seem to be limited to macOS for this. 编辑:正如Joakim Danielson指出的那样,您将需要Python运行时,并且它似乎在iOS中不可用,因此您似乎仅限于macOS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM