如何在 Swift 3.0 中使用 Process 调用外部命令?

发布于 2022-09-04 00:45:22 字数 1118 浏览 14 评论 0

在做个监控剪贴板的程序,如果复制的是需求网址就直接调用外部命令执行。想好了就动手,监控剪贴板这块儿很快搞定,问题出在使用 Process (原 NSTask)调用外部命令上。

先上代码(全部代码在 GitHub):

let process = Process()

let outpipe = Pipe()
process.standardOutput = outpipe
let errpipe = Pipe()
process.standardError = errpipe

process.launchPath = "/usr/local/bin/acmpv"
process.arguments = ["-f=mp4", copiedString]
process.launch()

let outdata = outpipe.fileHandleForReading.availableData
let outputString = String(data: outdata, encoding: String.Encoding.utf8) ?? ""
NSLog("Ouput: %@", outputString)

let errdata = errpipe.fileHandleForReading.availableData
let errString = String(data: errdata, encoding: String.Encoding.utf8) ?? ""
NSLog("Err: %@", errString)

process.waitUntilExit()

运行后并没有执行命令,而是在 console 输出:

warning: the gestalt selector gestaltsystemversion is returning 10.9.0 instead of 10.12.0...

在 Google 上搜索半天没有一条有用的。请问如何正确的在 Swift 中调用外部命令?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙温凉少女 2022-09-11 00:45:22

func execShellScript(path:String,mode:String,script:String)->String{

let task = Process()

task.launchPath = path

task.arguments = [mode,script]

let pipe = Pipe()

task.standardOutput = pipe

//task.standardError=pipe

task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()

let output: String = String(data: data, encoding: String.Encoding.utf8)!

return output

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文