Skip to content

Instantly share code, notes, and snippets.

@PaulChana
Created October 17, 2016 09:12
Show Gist options
  • Select an option

  • Save PaulChana/74c7f009e23492fb14bd92e0d82d5268 to your computer and use it in GitHub Desktop.

Select an option

Save PaulChana/74c7f009e23492fb14bd92e0d82d5268 to your computer and use it in GitHub Desktop.
NSTask Async output to NSTaskView
NSMutableArray *arguments = [[NSMutableArray alloc] init];
[arguments addObject:[[NSBundle mainBundle] pathForResource:@"MyScript" ofType:@"py"]];
[arguments addObject:@"--verbose"]; // Any arguments you want here...
NSTask* task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/python";
task.arguments = arguments;
NSMutableDictionary *defaultEnv = [[NSMutableDictionary alloc] initWithDictionary:[[NSProcessInfo processInfo] environment]];
[defaultEnv setObject:@"YES" forKey:@"NSUnbufferedIO"] ;
task.environment = defaultEnv;
task.standardOutput = [NSPipe pipe];
[[task.standardOutput fileHandleForReading] setReadabilityHandler:^(NSFileHandle *file) {
NSData *data = [file availableData]; // this will read to EOF, so call only once
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Task output! %@", string);
dispatch_async(dispatch_get_main_queue(), ^{
_logField.string = [_logField.string stringByAppendingString: string];
[_logField scrollRangeToVisible: NSMakeRange(_logField.string.length, 0)];
});
}];
[task launch];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment