I have a java program running in the background of my swift program. The java program can read user input in a command line. How can I pass "commands", or text line into the jar after it has been launched?
Just like the way the program down below read from the java program, how can I then "reply" to it?
let b = Bundle.main
let path = b.path(forResource: "myjar", ofType: "jar")!
NSLog("%#", "jar path : \(path)")
task.launchPath = "/usr/bin/java"
task.arguments = ["-jar", path]
let pipe = Pipe()
task.standardOutput = pipe
let errorPipe = Pipe()
task.standardError = errorPipe
task.launch()
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var progressObserver : NSObjectProtocol!
progressObserver = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NSFileHandleDataAvailable,
object: outHandle, queue: nil){
notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = String(data: data, encoding: String.Encoding.utf8) {
NSLog("%#", str)
}
outHandle.waitForDataInBackgroundAndNotify()
} else { NotificationCenter.default.removeObserver(progressObserver)
}
}
I then tried the following without luck:
pipe.fileHandleForWriting.write("text to send to java program".data(using: String.Encoding.utf8)
You're pretty close. If you just added the code pipe.fileHandleForWriting.write("text to send to java program"... that's not going to work because that pipe is the one you assigned to standardOutput.
You need to create yet another Pipe object, assign it to standardInput, and write to that:
...
>> let inputPipe = Pipe()
>> task.standardInput = inputPipe
task.launch()
>> inputPipe.fileHandleForWriting.write("text to send to java program".data(using: String.Encoding.utf8)
...
Related
I have this code to continously read the output of a started process:
let task = Process()
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
let pipe = Pipe()
let errorPipe = Pipe()
task.standardOutput = pipe
task.standardError = errorPipe
let outHandle = pipe.fileHandleForReading
let errorHandle = errorPipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
errorHandle.waitForDataInBackgroundAndNotify()
var updateObserver: NSObjectProtocol!
updateObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandle, queue: nil, using: { notification in
let data = outHandle.availableData
if !data.isEmpty {
if let str = String(data: data, encoding: .utf8) {
print(str) // This is differently here.
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
NotificationCenter.default.removeObserver(updateObserver!)
}
})
var errorObserver: NSObjectProtocol!
errorObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: errorHandle, queue: nil, using: { notification in
let data = errorHandle.availableData
if !data.isEmpty {
if let str = String(data: data, encoding: .utf8) {
print(str) // This is differently here.
}
errorHandle.waitForDataInBackgroundAndNotify()
} else {
NotificationCenter.default.removeObserver(errorObserver!)
}
})
var taskObserver : NSObjectProtocol!
taskObserver = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification, object: task, queue: nil, using: { notification in
print("terminated")
NotificationCenter.default.removeObserver(taskObserver!)
})
task.launch()
Now this works for processes that print a new line with every change.
What does not work is to get outputs of processes that edit already printed lines (changin percentage or something like that).
In that case, the pipe is not pushing anything.
How would I handle that case. I thought about doing the output into a file, read that and at the end deleting it. Is that a possible solution?
I want to execute a Terminal command in my Application and redirect the Terminal output of this command to a TextView (content_scroller). If I run the Application with Apple+R from within Xcode the Progress of this Terminal command is refreshed as it should. But ... If I started the Application the normal way only the first line of terminal output is shown but there is no refresh/new lines anymore. But why? Is there a way to loop the request of the actual output? Here is mit Swift 5 Code:
func syncShellExec(path: String, args: [String] = []) {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let filelHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
process.launch()
filelHandler.readabilityHandler = { pipe in
let data = pipe.availableData
if let line = String(data: data, encoding: .utf8) {
DispatchQueue.main.sync {
self.content_scroller.string += line
self.content_scroller.scrollToEndOfDocument(nil)
}
}
process.waitUntilExit()
filelHandler.readabilityHandler = nil
}
Should be able to direct output straight to text view if I understand your question correctly. Something like the following outputs an error (I didn't test it.)
import Cocoa
func syncShellExec(path: String, args: [String] = []) {
var status : Int32
var dataRead : Data
var stringRead :String?
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let txtView = NSTextView()
let fileHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
process.launch()
process.waitUntilExit()
status = process.terminationStatus
dataRead = fileHandler.readDataToEndOfFile()
stringRead = String.init(data: dataRead, encoding: String.Encoding.utf8)
if (status != 0) {
txtView.string.append("Terminated with error.\n")
txtView.string.append(stringRead!)
}
}
I'm using an NSTask to run rsync, and I'd like the status to show up in the text view of a scroll view inside a window. Right now I have this:
let pipe = NSPipe()
task2.standardOutput = pipe
task2.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSASCIIStringEncoding)! as String
textView.string = output
And that get's me the some of the statistics about the transfer, but I'd like to get the output in real time, like what get's printed out when I run the app in Xcode, and put it into the text view. Is there a way to do this?
Since macOS 10.7, there's also the readabilityHandler property on NSPipe which you can use to set a callback for when new data is available:
let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]
let pipe = NSPipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.readabilityHandler = { pipe in
if let line = String(data: pipe.availableData, encoding: NSUTF8StringEncoding) {
// Update your view with the new text here
print("New ouput: \(line)")
} else {
print("Error decoding data: \(pipe.availableData)")
}
}
task.launch()
I'm surprised nobody mentioned this, as it's a lot simpler.
(See Patrick F.'s answer for an update to Swift 3/4.)
You can read asynchronously from a pipe, using notifications.
Here is a simple example demonstrating how it works, hopefully that
helps you to get started:
let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]
let pipe = NSPipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var obs1 : NSObjectProtocol!
obs1 = NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification,
object: outHandle, queue: nil) { notification -> Void in
let data = outHandle.availableData
if data.length > 0 {
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) {
print("got output: \(str)")
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
print("EOF on stdout from process")
NSNotificationCenter.defaultCenter().removeObserver(obs1)
}
}
var obs2 : NSObjectProtocol!
obs2 = NSNotificationCenter.defaultCenter().addObserverForName(NSTaskDidTerminateNotification,
object: task, queue: nil) { notification -> Void in
print("terminated")
NSNotificationCenter.defaultCenter().removeObserver(obs2)
}
task.launch()
Instead of print("got output: \(str)") you can append the received
string to your text view.
The above code assumes that a runloop is active (which is the case
in a default Cocoa application).
This is the update version of Martin's answer above for the latest version of Swift.
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]
let pipe = Pipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var obs1 : NSObjectProtocol!
obs1 = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable,
object: outHandle, queue: nil) { notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
print("got output: \(str)")
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
print("EOF on stdout from process")
NotificationCenter.default.removeObserver(obs1)
}
}
var obs2 : NSObjectProtocol!
obs2 = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification,
object: task, queue: nil) { notification -> Void in
print("terminated")
NotificationCenter.default.removeObserver(obs2)
}
task.launch()
I have an answer which I believe is more clean than the notification approach, based on a readabilityHandler. Here it is, in Swift 5:
class ProcessViewController: NSViewController {
var executeCommandProcess: Process!
func executeProcess() {
DispatchQueue.global().async {
self.executeCommandProcess = Process()
let pipe = Pipe()
self.executeCommandProcess.standardOutput = pipe
self.executeCommandProcess.launchPath = ""
self.executeCommandProcess.arguments = []
var bigOutputString: String = ""
pipe.fileHandleForReading.readabilityHandler = { (fileHandle) -> Void in
let availableData = fileHandle.availableData
let newOutput = String.init(data: availableData, encoding: .utf8)
bigOutputString.append(newOutput!)
print("\(newOutput!)")
// Display the new output appropriately in a NSTextView for example
}
self.executeCommandProcess.launch()
self.executeCommandProcess.waitUntilExit()
DispatchQueue.main.async {
// End of the Process, give feedback to the user.
}
}
}
}
Please note that the Process has to be a property, because in the above example, given that the command is executed in background, the process would be deallocated immediately if it was a local variable. Thanks for your attention.
I have built a command line tool, at some point, I need to execute a curl command. I'm creating the script that should be executed, but I don't know how.
I'm able to create the script and printing it out, but I'm not being able to execute it.
It looks something like: curl https://api.github.com/zen
Please ask me anything if it's not clear. I appreciate your help.
#!/usr/bin/env swift
import Foundation
func run(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
run("curl", "https://api.github.com/zen")
You can run a Terminal command from Swift using NSTask (now called Process in Swift 3): If you need output, add let output = handle.readDataToEndOfFile() at the end. Here's the whole thing wrapped in a function (the launchPath would be /usr/bin/curl):
func runTask(launchPath: String, flags: [String]) -> String {
let task = Process()
let pipe = Pipe()
task.launchPath = launchPath
task.arguments = flags
task.standardOutput = pipe
let handle = pipe.fileHandleForReading
task.launch()
return String(data: handle.readDataToEndOfFile(), encoding: .utf8) ?? ""
}
In your case though, you might want to have a look at URLSession and URLRequest (superseding NSURLRequest). To create a request to your URL and credentials, you would simply do:
var request = URLRequest(url:URL(string: "https://api.github.com/zen")!)
request.setValue("application/vnd.github.v3.raw", forHTTPHeaderField: "Accept")
request.setValue("token USERTOKEN", forHTTPHeaderField: "Authorization")
let session = URLSession(configuration: .default)
session.dataTask(with: request, completionHandler: {(data, response, error) in
guard let data = data, error == nil else {
print("Error: \(error.debugDescription)")
return
}
guard let output = String(data: data, encoding: .utf8) as String? else {
print("Unable to format output data")
return
}
print(output)
}).resume()
I'm a complete swift noob. Using this code in xcode I get the result I need. I created a command line binary "menubar" that takes several arguments. I normally run it in the terminal "/bin/menubar getip", "/bin/menubar/getuser". I want to create a function based on the following working code.
import Cocoa
import Foundation
var task:NSTask = NSTask()
var pipe:NSPipe = NSPipe()
task.launchPath = "/bin/menubar"
task.arguments = ["getip"]
task.standardOutput = pipe
task.launch()
var handle = pipe.fileHandleForReading
var data = handle.readDataToEndOfFile()
var result_s = NSString(data: data, encoding: NSUTF8StringEncoding)
print(result_s)
I want to convert it to a function.
func commmand (argument: String) -> String
{
let task:NSTask = NSTask()
let pipe:NSPipe = NSPipe()
task.launchPath = "/bin/menubar"
task.arguments = ["argument"]
task.standardOutput = pipe
task.launch()
let handle = pipe.fileHandleForReading
let data = handle.readDataToEndOfFile()
let result_s = NSString(data: data, encoding: NSUTF8StringEncoding)
return result_s
}
commmand getip
Try this:
func commmand(argument: String) -> String
{
let task:NSTask = NSTask()
let pipe:NSPipe = NSPipe()
task.launchPath = "/bin/menubar"
task.arguments = [argument]
task.standardOutput = pipe
task.launch()
let handle = pipe.fileHandleForReading
let data = handle.readDataToEndOfFile()
let result_s = String(data: data, encoding: NSUTF8StringEncoding)!
return result_s
}
print(commmand("getip"))