如何在运行时从字符串中运行代码?

时间:2017-07-10 21:38:11

标签: swift concurrency runtime nstask

首先,我知道Apple拒绝包含类似内容的应用程序。这只是出于个人目的。

我尝试了以下示例:

import Foundation

var instructions: String = "let str = \"Hello\"\nprint(\"\\(str) world\")\n"
let process: Process = Process()

process.launchPath = "/usr/bin/swift"

let inpipe: Pipe = Pipe()
let outpipe: Pipe = Pipe()

inpipe.fileHandleForWriting.write(instructions.data(using: String.Encoding.utf8, allowLossyConversion: true)!)

process.standardInput = inpipe
process.standardOutput = outpipe
process.launch()
process.waitUntilExit() // never ends
process.standardInput = Pipe()

let data = outpipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)

我在Mac上运行程序。该计划永远不会结束。我不知道错误在哪里。

0 个答案:

没有答案