我正在尝试在 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 脚本中将命令链接在一起,以便数据从一个命令流到下一个命令?我尝试了分配 standardIn
和 standardOut
以及在两个 Process
之间使用 Pipe()
的各种组合,但要么我做错了,或者我没有将正确的部分连接在一起。
最佳答案
我在 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")
关于swift - 在 Swift 脚本中使用管道链接 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711408/