有没有一种方法可以让我运行Shell脚本,并在NSTextView中显示输出?我根本不希望用户对shell脚本有任何输入,因为只是调用来编译大量文件。到目前为止,shell脚本部分可以正常工作,但是我无法弄清楚如何运行它并在NSTextView中显示输出。我知道可以使用system()和NSTask运行shell脚本,但是如何将其输出到NSTextView中呢?

最佳答案

如果要通配符扩展,则将unix命令传递到/ bin / sh

- (NSString *)unixSinglePathCommandWithReturn:(NSString *) command {
    // performs a unix command by sending it to /bin/sh and returns stdout.
    // trims trailing carriage return
    // not as efficient as running command directly, but provides wildcard expansion

    NSPipe *newPipe = [NSPipe pipe];
    NSFileHandle *readHandle = [newPipe fileHandleForReading];
    NSData *inData = nil;
    NSString* returnValue = nil;

    NSTask * unixTask = [[NSTask alloc] init];
    [unixTask setStandardOutput:newPipe];
    [unixTask setLaunchPath:@"/bin/csh"];
    [unixTask setArguments:[NSArray arrayWithObjects:@"-c", command , nil]];
    [unixTask launch];
    [unixTask waitUntilExit];
    int status = [unixTask terminationStatus];

    while ((inData = [readHandle availableData]) && [inData length]) {

        returnValue= [[NSString alloc]
                      initWithData:inData encoding:[NSString defaultCStringEncoding]];

        returnValue = [returnValue substringToIndex:[returnValue length]-1];

        NSLog(@"%@",returnValue);
    }

    return returnValue;

}

关于cocoa - 在Cocoa中获取Shell脚本的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2842682/

10-10 20:36