【问题标题】:Mac OS X: Execute scripts with hooks from an applicationMac OS X:使用来自应用程序的钩子执行脚本
【发布时间】:2013-04-07 13:57:04
【问题描述】:

我正在构建一个监控某事™ 的可可应用程序,并且我计划为用户提供一些挂钩。因此,我想让用户能够将具有指定名称(比如说 after_event)的脚本(Bash、Ruby、Python 等)放入应用程序支持目录,并且该脚本在我的代码中的某个事件之后执行。理想情况下,我可以将一些变量传递给脚本,以便脚本知道发生了什么。

对此有何想法?

所以问题一是:我如何获得应用程序支持“SDK 方式”的路径?问题二是:如何使用 THAT_APPEND="foo" 之类的变量执行脚本?

谢谢, 菲利普

【问题讨论】:

标签: macos cocoa scripting hook


【解决方案1】:

因为分享是关心这里是执行脚本的方法:

-(void) runScript:(NSString*)scriptName withVariables:(NSDictionary *)variables
{
NSString *appSupportPath = [NSFileManager defaultManager] applicationSupportDirectory];

        NSArray *arguments;
        NSString* newpath = [NSString stringWithFormat:@"%@/%@",appSupportPath, scriptName];
        if ([[NSFileManager defaultManager]fileExistsAtPath:newpath]){
            NSTask *task = [[NSTask alloc] init];
            [task setLaunchPath: newpath];

            NSLog(@"Executing hook: %@",newpath);
            arguments = [NSArray arrayWithObjects:newpath, nil];
            [task setArguments: arguments];

            [task setEnvironment:variables];

            NSPipe *pipe;
            pipe = [NSPipe pipe];
            [task setStandardOutput: pipe];

            NSFileHandle *file;
            file = [pipe fileHandleForReading];

            [task launch];

            NSData *data;
            data = [file readDataToEndOfFile];

            NSString *string;
            string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
            NSLog (@"script returned:\n%@", string);
        }

}

}

更新:我将代码更新为更通用。现在 NSTask 将告诉内核直接执行脚本,这样您的用户就不能在线使用 Bash 脚本,还可以使用她喜欢的 python、perl、php。她唯一需要使用的是该文件中的Shebang

NSFileManager 类别可以在here 找到。

【讨论】:

    【解决方案2】:

    寻找NSTask documentation。有一个您可以操纵的环境成员。同样以-name = value 的形式添加命令行参数应该很简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多