在ObjC中获取shell命令的输出 [英] Get output of shell command in ObjC

查看:208
本文介绍了在ObjC中获取shell命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读解决方案这样做使用NSTask:他们都看起来非常长...所以我设法做同样的事情使用这个代码(它获得标准输出和标准错误):

I've read solutions for doing this using NSTask: they all look very very long... So I managed to do the exact same thing using this code (which gets both standard output and standard error):

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:@""];

使用此解决方案是否有任何缺点?是否有更短的方法来过滤输出?

Are there any drawbacks using this solution? Is there a shorter way to filter the output?

推荐答案


使用这个解决方案有什么缺点吗?是否有更短的方式
过滤输出?

Are there any drawbacks using this solution? Is there a shorter way to filter the output?

是的,有很多缺点。你依赖于一个实现细节, description 会神奇地返回任务的命令行和输出。这不是文档声明的, description 真的可以在调试/日志以外使用。

Yes, many drawbacks. You are relying on an implementation detail that description will magically return the task's command line and output. That is not claimed by the documentation nor is description really acceptable to use beyond debugging/logging.

该代码只是为了方便起见。

I.e. that code only works by convenience.

但是这个代码不是真的有效。如果你运行的命令从不退出或花费一段时间运行或产生大量的输出,那么该代码很可能实际上没有抓住任何输出或抛出截断的输出。

But that code isn't really working. If the command you were to run never exits or takes a while to run or produces a massive amount of output, then that code is likely to not actually grab any of the output at all or to spew truncated output.

有一个原因,为什么使用 NSTask 的示例往往有点冗长。管理进程之间的I / O实际上相当困难,并且有很多不同的选项需要考虑。

There is a reason why the examples that use NSTask tend to be a bit lengthy. Managing I/O between processes is actually quite hard and there are a lot of different options that need to be taken into account.

这篇关于在ObjC中获取shell命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆