Cocoa/Objective-C Shell 命令行执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1475182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:15:21  来源:igfitidea点击:

Cocoa/ Objective-C Shell Command Line Execution

objective-ccocoamacosunixcommand-line

提问by Tom

This is probably a stupid question, but how can I execute a shell command from my Cocoa app?

这可能是一个愚蠢的问题,但如何从我的 Cocoa 应用程序执行 shell 命令?

I have the command as a string "command", but can easily manipulate data as needed.

我将命令作为字符串“命令”,但可以根据需要轻松操作数据。

There is no need to get a returned output value.

无需获取返回的输出值。

回答by Quinn Taylor

NSTaskis pretty easy to do this with. For a synchronous call, you can use something like this fragment:

NSTask很容易做到这一点。对于同步调用,您可以使用如下片段:

NSString *path = @"/path/to/executable";
NSArray *args = [NSArray arrayWithObjects:..., nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

The -waitUntilExitcall makes sure it finishes before proceeding. If the task can be asynchronous, you can remove that call and just let the NSTask do it's thing.

-waitUntilExit调用确保它在继续之前完成。如果任务可以是异步的,您可以删除该调用并让 NSTask 完成它的工作。

回答by BJ Homer

If you just want to run something and don't care about the output or return code (for example, you want to touch a file), you can just do

如果你只是想运行一些东西而不关心输出或返回代码(例如,你想触摸一个文件),你可以这样做

system("touch myfile.txt");

Easy as that.

就这么简单。

回答by Terry Wilcox

NSTask

任务

Using the NSTask class, your program can run another program as a subprocess and can monitor that program's execution.

使用 NSTask 类,您的程序可以将另一个程序作为子进程运行,并且可以监视该程序的执行。