我有一个简单的 Python 脚本,它询问您的姓名,然后将其吐出:
def main():
print('Enter your name: ')
for line in sys.stdin:
print 'You entered: ' + line
很简单的东西!在 OS X 终端中运行它时,效果很好:
$ python nameTest.py
Enter your name:
Craig^D
You entered: Craig
但是,当尝试通过 运行此过程时NSTask
,只有在 Python 脚本中添加了额外的 flush() 调用时才会出现标准输出。
这就是我NSTask
配置管道和管道的方式:
NSTask *_currentTask = [[NSTask alloc] init];
_currentTask.launchPath = @"/usr/bin/python";
_currentTask.arguments = [NSArray arrayWithObject:@"nameTest.py"];
NSPipe *pipe = [[NSPipe alloc] init];
_currentTask.standardOutput = pipe;
_currentTask.standardError = pipe;
dispatch_queue_t stdout_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
__block dispatch_block_t checkBlock;
checkBlock = ^{
NSData *readData = [[pipe fileHandleForReading] availableData];
NSString *consoleOutput = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.consoleView appendString:consoleOutput];
});
if ([_currentTask isRunning]) {
[NSThread sleepForTimeInterval:0.1];
checkBlock();
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
NSData *readData = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *consoleOutput = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
[self.consoleView appendString:consoleOutput];
});
}
};
dispatch_async(stdout_queue, checkBlock);
[_currentTask launch];
但是在运行时NSTask
,它是这样显示的(它最初是空白的,但在输入我的名字并按 CTRL+D 后,它会立即完成):
Craig^DEnter your name:
You entered: Craig
所以,我的问题是:如何在不需要 Python 脚本中的额外 flush() 语句的情况下stdout
从 my中读取?NSTask
为什么Enter your name:提示在运行时不会立即出现NSTask
?