有没有办法让我运行一个 shell 脚本,并在 NSTextView 中显示输出?我根本不希望用户向 shell 脚本输入任何内容,因为它只是被调用来编译大量文件。到目前为止,shell 脚本部分工作正常,但我只是不知道如何运行它并在 NSTextView 中显示输出。我知道可以使用 system() 和 NSTask 运行 shell 脚本,但是如何将其输出到 NSTextView 中?
问问题
1778 次
2 回答
3
如果您想要通配符扩展,请将您的 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;
}
于 2010-05-16T06:54:08.233 回答
1
NSTask
具有setStandardOutput
接受NSFileHandle
或接受NSPipe
对象的方法。因此,如果您创建NSPipe
对象并将其设置为NSTask
's standardOutput
,那么您可以使用NSPipe
'sfileHandleForReading
从中获取NSFileHandle
,反过来,您将能够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;
}
于 2010-05-16T06:18:21.757 回答