代码之家  ›  专栏  ›  技术社区  ›  Tristan

获取cocoa中shell脚本的输出

  •  2
  • Tristan  · 技术社区  · 15 年前

    有没有一种方法可以让我运行shell脚本,并在nstextview中显示输出?我根本不希望用户向shell脚本输入任何信息,因为它只是被调用来编译一个buch文件。到目前为止,shell脚本部分工作得很好,但我还不能确定如何运行它并在nstextview中显示输出。我知道shell脚本可以使用system()和nstask运行,但如何将其输出到nstextview中?

    2 回复  |  直到 11 年前
        1
  •  3
  •   ra1nmaster    11 年前

    如果需要通配符扩展,请将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;
    
    }
    
        2
  •  1
  •   Peter Hosey    15 年前

    NSTask setStandardOutput 方法接受 NSFileHandle NSPipe 对象。所以如果你创造 NSPIPE 对象并将其设置为 NSTASK standardOutput 然后你可以用 NSPIPE fileHandleForReading 得到 NSF文件句柄 反过来,你可以 readDataToEndOfFile readDataOfLength: 你想要。所以类似这样的事情可以做到(代码未经测试):

    - (void)setupTask {
      // assume it's an ivar
      standardOutputPipe = [[NSPipe alloc] init];
      [myTask setStandardOutput:standardOutputPipe];
      // other setup code goes below
    }
    
    // reading data to NSTextField
    - (void)updateOutputField {
      NSFileHandle *readingFileHandle = [standardOutputPipe fileHandleForReading];
      NSData *newData;
      while ((newData = [readingFileHandle availableData])) {
        NSString *newString = [[[NSString alloc] initWithData:newData encoding: NSASCIIStringEncoding] autorelease];
        NSString *wholeString = [[myTextField stringValue] stringByAppendingString:newString];
        [myTextField setStringValue:wholeString];
      }
      [standardOutputPipe release];
      standardOutputPipe = nil;
    }