gpt4 book ai didi

swift - 在 swift 中使用 NSTask 执行终端命令

转载 作者:可可西里 更新时间:2023-11-01 01:35:26 24 4
gpt4 key购买 nike

你好,我正在尝试用 swift 编写一个简单的程序来执行这个在 Dock 中添加空白的命令:

defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}'; killall 码头

这是我使用的代码:

    let task = NSTask()
task.launchPath = "/usr/bin/defaults"
task.arguments = ["write","com.apple.dock","persistent-apps","-array-add","'{\"tile-type\"=\"spacer-tile\";}';","killall Dock"]
let pipe = NSPipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
print(output)

我没有收到任何错误,但什么也没发生。有人可以帮帮我吗?

最佳答案

这是对我有用的代码:

    let task = NSTask()
task.launchPath = "/usr/bin/defaults"
task.arguments = ["write","com.apple.dock","persistent-apps","-array-add","{\"tile-type\"=\"spacer-tile\";}"]
let pipe = NSPipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()

let task2 = NSTask()
task2.launchPath = "/usr/bin/killall"
task2.arguments = ["Dock"]
let pipe2 = NSPipe()
task2.standardOutput = pipe2
task2.standardError = pipe2
task2.launch()
task2.waitUntilExit()


let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
print(output)

关于swift - 在 swift 中使用 NSTask 执行终端命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38413269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com