gpt4 book ai didi

swift - NSTask (whoami) 到字符串,到 NSTask (cp) 失败 - Swift

转载 作者:行者123 更新时间:2023-11-30 13:56:22 26 4
gpt4 key购买 nike

我正在尝试在存档之前将 Mac 的地址簿复制到保存位置。这是我的代码:

 // whoami
let whoam : NSTask = NSTask()
whoam.launchPath = "/usr/bin/whoami"

// pipe whoami| NSString
let UltimPipe : NSPipe = NSPipe()
let UltimPipeLisible : NSFileHandle = UltimPipe.fileHandleForReading
whoam.standardOutput = UltimPipe
// lancement
whoam.launch()

// lecture de la sortie
let DonSortie : NSData = UltimPipeLisible.readDataToEndOfFile()
let Sortie : String? = String(data: DonSortie, encoding:
NSUTF8StringEncoding)

if Sortie == nil
{
print("Résultat de sortie non-valide")
let MonAlerte:NSAlert = NSAlert()
MonAlerte.messageText = "Aucun élement trouvé."
MonAlerte.informativeText = ""
MonAlerte.runModal()
exit(1)
}

let ligne : String = Sortie!
print (ligne)

let source = "/Users/"+ligne+"/Library/Application Support/AddressBook"
let destin = "/Users/"+ligne+"/Desktop/test/"


//cp
let duTache : NSTask = NSTask()
duTache.launchPath = "/bin/cp"
duTache.arguments = [ "-r", source, " ", destin ]
print (duTache.arguments)

let ifcPipe : NSPipe = NSPipe()
duTache.standardOutput = ifcPipe

// lancement
duTache.launch()

返回的错误是:

usage: cp [-R [-H |...]

看起来我有语法问题,并且当我打印 duTache 的参数时 (print (duTache.arguments)),答案是:

Optional(["-r", "/Users/username\n/Library/Application Support/AddressBook", " ", "/Users/username\n/Desktop/test/"])

也许如果我删除用户名后面的“\n”,操作就可以完成?有谁知道该怎么做吗?

感谢您阅读我的帖子。

最佳答案

var ligne = "username\n"
print(ligne,0)
/*
username
0
*/
let newLine = ligne.removeAtIndex(ligne.endIndex.predecessor()) // newLine is "\n"
print(ligne,0)
/*
username 0
*/

关于swift - NSTask (whoami) 到字符串,到 NSTask (cp) 失败 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33571649/

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