我试图在Swift脚本中将shell命令链接在一起.有问题的实际命令是gource
管道输出的输出ffmpeg
,但这里是一个简化的,人为的例子,我正在尝试做什么:
let echo = Process() echo.launchPath = "/usr/bin/env" echo.arguments = ["echo", "foo\nbar\nbaz\nbaz", "|", "uniq"] let pipe = Pipe() echo.standardOutput = pipe echo.launch() echo.waitUntilExit() // Get the data let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) print(output ?? "no output")
预期产量:
foo bar baz
实际产量:
foo bar baz baz | uniq
将|
被解释为最后一个参数的一部分.如何将命令链接在一起,以便数据在Swift脚本中从一个流向另一个?我尝试了在两个es 之间分配standardIn
和standardOut
使用的各种组合,但要么我做错了,要么我没有将正确的部分连接在一起.Pipe()
Process
我在zadr的帮助下得到了答案:
import Foundation let pipe = Pipe() let echo = Process() echo.launchPath = "/usr/bin/env" echo.arguments = ["echo", "foo\nbar\nbaz\nbaz"] echo.standardOutput = pipe let uniq = Process() uniq.launchPath = "/usr/bin/env" uniq.arguments = ["uniq"] uniq.standardInput = pipe let out = Pipe() uniq.standardOutput = out echo.launch() uniq.launch() uniq.waitUntilExit() let data = out.fileHandleForReading.readDataToEndOfFile() let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) print(output ?? "no output")