swift - 在 Swift 脚本中使用管道链接 shell 命令

标签 swift shell scripting

我正在尝试在 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 脚本中将命令链接在一起,以便数据从一个命令流到下一个命令?我尝试了分配 standardInstandardOut 以及在两个 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/

相关文章:

swift - CollectionView,两个按钮无法通信 - Swift 4

ios - 在 Button Click Swift 上重复附加到数组

python - python可以生成可执行的shell脚本吗?

powershell - 是否可以使 cmdlet 与同时通过管道传输到其中的所有项目一起工作?

python - 尝试通过脚本在 Spotfire 中打开和关闭显示/隐藏项目过滤器

ios - 如何使用 Swift 在 UIView(不是全屏)中播放视频?

ios - 触发按钮以在 swift3 xcode 8 ios 10 中更改 UITextView 中的文本

linux - 使用sed替换文件中的内联字符串

linux - 使用 sed 设置变量适用于命令行,但不适用于 bash 脚本

javascript - Unity脚本全局变量