[英]Get output of shell command in ObjC
我已经阅读了使用 NSTask 执行此操作的解决方案:它们看起来都很长......所以我设法使用此代码做了完全相同的事情(它同时获得标准 output 和标准错误):
NSTask *task = [NSTask new];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:@[ @"-c", @"aCommand"]];
NSString *stringToRemove = [task description];
[task launch];
NSString *output = [[task description] stringByReplacingOccurrencesOfString:stringToRemove withString:@""];
使用此解决方案有什么缺点吗? 有没有更短的方法来过滤 output?
使用此解决方案是否有任何弊端? 有没有更短的方法来过滤输出?
是的,有很多缺点。 您所依赖的实现细节, description
将神奇地返回任务的命令行和输出。 该文档没有要求保护,也不能接受除调试/记录之外的description
。
即,该代码仅出于方便而起作用。
但是该代码并没有真正起作用。 如果您要运行的命令从不退出,或者需要一段时间才能运行或产生大量输出,则该代码很可能根本无法真正获取任何输出或喷出截断的输出。
使用NSTask
的示例有些冗长是有原因的。 实际上,在进程之间管理I / O非常困难,并且需要考虑许多不同的选项。
如果您的目标只是运行命令并等待它退出(例如从 CLI 应用程序中的 shell 命令获取信息),您可以使用以下命令(启用 ARC):
// Start the task with path and arguments.
NSTask* task = [NSTask new];
[task setExecutableURL:[NSURL fileURLWithPath:@"/path/to/task"]];
[task setArguments:@[@"your", @"arguments", @"here"]];
// Intercept the standard output of the process.
NSPipe* output = [NSPipe pipe];
[task setStandardOutput:output];
// Launch and wait until finished.
[task launch];
[task waitUntilExit];
// Read all data from standard output as NSData.
NSData* resultData = [[output fileHandleForReading] readDataToEndOfFile];
// Convert NSData to string (could be combined with above when ARC used).
NSString* result = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
这在长度上似乎并不合理(并且可能会缩短,尽管为了便于阅读我将其保留),如果您经常使用它,您可以将其抽象为 function。
我还注意到,由于您没有在代码中重定向 output,它还会将 output 打印到控制台,这可能是无意的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.