gpt4 book ai didi

python - 从进程的标准输出读取时,NSTask 需要刷新,终端不需要

转载 作者:行者123 更新时间:2023-11-28 22:01:14 27 4
gpt4 key购买 nike

我有一个简单的 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 运行此过程时,仅当将额外的 flush() 调用添加到 Python 脚本时才会出现标准输出。

这就是我配置 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

所以,我的问题是:我怎样才能从我的 NSTask 中读取 stdout 而不需要在我的 Python 中使用额外的 flush() 语句脚本?为什么 Enter your name: 提示在作为 NSTask 运行时不会立即出现?

最佳答案

当 Python 发现它的标准输出是终端时,它会安排在脚本从 sys.stdin 读取时自动刷新 sys.stdout。当您使用 NSTask 运行脚本时,脚本的标准输出是管道,而不是终端。

更新

有一个特定于 Python 的解决方案。您可以将 -u 标志传递给 Python 解释器(例如 _currentTask.arguments = @[ @"-u", @"nameTest.py"];),它告诉 Python 根本不要缓冲标准输入、标准输出或标准错误。你也可以在进程的环境中设置PYTHONUNBUFFERED=1来达到同样的效果。

原创

适用于任何程序的更通用的解决方案使用所谓的“伪终端”(或者,历史上称为“伪电传打字机”),我们简称为“pty”。 (事实上​​,这就是 Terminal 应用程序本身所做的事情。它是一种罕见的 Mac,它具有连接到串行端口的物理终端或电传打字机!)

每个pty其实就是一对虚拟设备:一个slave设备和一个master设备。你写给master的字节,你可以从slave读取,反之亦然。所以这些设备更像是套接字(双向的)而不是管道(单向的)。此外,pty 还允许您设置终端 I/O 标志(或“termios”),以控制从属设备是否回显其输入,是一次传递一行还是一次传递一个字符,等等。

无论如何,您可以使用openpty 函数轻松打开主/从对。这里有一个小类,您可以使用它来使 NSTask 对象使用从端作为任务的标准输入和输出。

NSTask+PTY.h

@interface NSTask (PTY)

- (NSFileHandle *)masterSideOfPTYOrError:(NSError **)error;

@end

NSTask+PTY.m

#import "NSTask+PTY.h"
#import <util.h>

@implementation NSTask (PTY)

- (NSFileHandle *)masterSideOfPTYOrError:(NSError *__autoreleasing *)error {
int fdMaster, fdSlave;
int rc = openpty(&fdMaster, &fdSlave, NULL, NULL, NULL);
if (rc != 0) {
if (error) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil];
}
return NULL;
}
fcntl(fdMaster, F_SETFD, FD_CLOEXEC);
fcntl(fdSlave, F_SETFD, FD_CLOEXEC);
NSFileHandle *masterHandle = [[NSFileHandle alloc] initWithFileDescriptor:fdMaster closeOnDealloc:YES];
NSFileHandle *slaveHandle = [[NSFileHandle alloc] initWithFileDescriptor:fdSlave closeOnDealloc:YES];
self.standardInput = slaveHandle;
self.standardOutput = slaveHandle;
return masterHandle;
}

@end

你可以这样使用它:

NSTask *_currentTask = [[NSTask alloc] init];
_currentTask.launchPath = @"/usr/bin/python";
_currentTask.arguments = @[[[NSBundle mainBundle] pathForResource:@"nameTest" ofType:@"py"]];

NSError *error;
NSFileHandle *masterHandle = [_currentTask masterSideOfPTYOrError:&error];
if (!masterHandle) {
NSLog(@"error: could not set up PTY for task: %@", error);
return;
}

然后您可以使用 masterHandle 从任务中读取和写入任务。

关于python - 从进程的标准输出读取时,NSTask 需要刷新,终端不需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com