0

I have a simple NSButton function executing a 'ls -la' command:

@IBAction func Convert(_ sender: NSButton) {
    let path = "/bin/ls"
    let arguments = ["-la"]
    sender.isEnabled = false
    let task = Process.launchedProcess(launchPath: path, arguments: arguments)
    task.waitUntilExit()
    sender.isEnabled = true
}

I need the stdout in my NSScrollView:

@IBOutlet weak var Output: NSScrollView!
Eric Melda
  • 13
  • 2
  • 1
    Possible duplicate of [Real time NSTask output to NSTextView with Swift](https://stackoverflow.com/questions/29548811/real-time-nstask-output-to-nstextview-with-swift) – Martin R Dec 12 '17 at 12:58
  • To set the _text_, you need a `@IBOutlet` of a `NSTextView` that's supposed to be inside the scroll view. If you just added a scroll view in your interface file, you should replace that with a NSTextView (which is automatically wrapped in a scroll view). You can then use `textView.string = "..."` to replace the text with the result of the output (see answer below). – ctietze Dec 13 '17 at 09:13

1 Answers1

1

You need a Pipe and a FileHandle

let path = "/bin/ls"
let arguments = ["-la"]
// sender.isEnabled = false
let task = Process()
task.launchPath = path
task.arguments = arguments
let outputPipe = Pipe()
task.standardOutput = outputPipe
task.launch()
task.waitUntilExit()
let data = (task.standardOutput as! Pipe).fileHandleForReading.readDataToEndOfFile()
let output = String(data:data, encoding: .utf8)!
print(output)
// sender.isEnabled = true

And please conform to the naming convention that variable and function / method names start with a lowercase letter.

vadian
  • 274,689
  • 30
  • 353
  • 361