gpt4 book ai didi

macos - NSFilehandle swift

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:07 25 4
gpt4 key购买 nike

我正在尝试将从命令行返回的信息作为字符串输入到我的程序中。这是我的代码,我尝试了一些其他变体但没有成功。

    let MyTask : NSTask = NSTask()
MyTask.launchPath = "/usr/bin/cal"
MyTask.arguments = ["04","2014"]
MyTask.launch()
MyTask.waitUntilExit()
var TheHandle = MyTask.standardOutput as NSFileHandle
println(TheHandle)
var Data = TheHandle.readDataToEndOfFile()
var DataAsString = NSString(data: Data,encoding: NSUTF8StringEncoding)
println(DataAsString)

输出

     April 2014
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

<_NSStdIOFileHandle: 0x6180000e4f80>
2014-11-14 23:22:40.014 Command Reader[6631:118648] *** -[_NSStdIOFileHandle readDataOfLength:]: Bad file descriptor

最佳答案

任务的标准输出必须设置为进程可以写入的文件句柄。对于父进程和子进程之间的通信,通常这样做用。子进程写入管道的写入端,而父进程从读取端读取:

let myTask  = NSTask()

myTask.launchPath = "/usr/bin/cal"
myTask.arguments = ["04","2014"]

let pipe = NSPipe()
myTask.standardOutput = pipe

myTask.launch()
myTask.waitUntilExit()

let theHandle = pipe.fileHandleForReading
let data = theHandle.readDataToEndOfFile()
if let dataAsString = NSString(data: data,encoding: NSUTF8StringEncoding) {
println(dataAsString)
} else {
println("could not convert output to string")
}

备注:

  • myTask.standardOutput 设置为管道本身。这导致进程写入 pipe.fileHandleForWriting,完成后关闭该文件描述符。如果文件描述符未关闭,则 theHandle.readDataToEndOfFile()在父进程中会无限期地等待。
  • 我使用了以小写字母开头的变量,这是 Swift 中的惯例。

如果你想将过程输出写入文件,那么你可以创建文件,将其作为文件句柄打开并将该句柄传递给 myTask.standardOutput:

let myTask  = NSTask()
myTask.launchPath = "/usr/bin/cal"
myTask.arguments = ["04","2014"]

let path = "/path/to/output.txt" // where the output should be written ...
if (!NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)) {
println("could not create file")
} else if let theHandle = NSFileHandle(forWritingAtPath: path) {
myTask.standardOutput = theHandle

myTask.launch()
myTask.waitUntilExit()
theHandle.closeFile()
} else {
println("could not open file")
}

关于macos - NSFilehandle swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943635/

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