当前位置: 代码迷 >> 综合 >> 【Mac】MacOS: shell script from application
  详细解决方案

【Mac】MacOS: shell script from application

热度:42   发布时间:2023-12-08 08:52:03.0

启动一个脚本

 

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/script/sh"];
[task setArguments:[NSArray arrayWithObjects:@"yourScript.sh", nil]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];[task launch];
[task release];

 

That would run the command /path/to/script/sh yourScript.sh. If you need any arguments for your script, you can add them to the array of arguments. The standard output will redirect all output to a pipe object, which you can hook into if you want to output to a file. The reason we need to use another NSPipe for input is to make NSLog work right instead of logging to the script.

 

 

**************

运行一个python脚本:

From this page, it looks like there are some some pretty complex threading concerns specific to embedding python. Is there a reason you couldn't just run these scripts in a separate process? For instance, the following -runBunchOfScripts method would run the script ten times (by calling -runPythonScript) on a parallel background queue, collecting the resulting outputs into an array of strings, and then calling your object back on the main thread once all the scripts has completed:

 

- (NSString*)runPythonScript
{NSTask* task = [[[NSTask alloc] init] autorelease];task.launchPath = @"/usr/bin/python";  NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"MyScript" ofType:@"py"];task.arguments = [NSArray arrayWithObjects: scriptPath, nil];// NSLog breaks if we don't do this...[task setStandardInput: [NSPipe pipe]];NSPipe *stdOutPipe = nil;stdOutPipe = [NSPipe pipe];[task setStandardOutput:stdOutPipe];NSPipe* stdErrPipe = nil;stdErrPipe = [NSPipe pipe];[task setStandardError: stdErrPipe];[task launch];        NSData* data = [[stdOutPipe fileHandleForReading] readDataToEndOfFile];[task waitUntilExit];NSInteger exitCode = task.terminationStatus;if (exitCode != 0){NSLog(@"Error!");return nil;}return [[[NSString alloc] initWithBytes: data.bytes length:data.length encoding: NSUTF8StringEncoding] autorelease];
}- (void)runBunchOfScripts
{dispatch_group_t group = dispatch_group_create();NSMutableArray* results = [[NSMutableArray alloc] init];for (NSUInteger i = 0; i < 10; i++){dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{NSString* result = [self runPythonScript];@synchronized(results){[results addObject: result];}});}dispatch_group_notify(group, dispatch_get_main_queue(), ^{[self scriptsDidFinishWithResults: results];dispatch_release(group);[results release];});
}- (void)scriptsDidFinishWithResults: (NSArray*)results
{NSLog(@"Do something with the results...");
}

 

 

 

  相关解决方案