在OSX应用程序中运行终端命令? [重复]

时间:2021-10-23 20:20:05

This question already has an answer here:

这个问题在这里已有答案:

Is there a way to programatically run OSX terminal commands from within an app.

有没有办法从应用程序中以编程方式运行OSX终端命令。

For example, if I wanted to list all files in mac terminal I would use 'ls'. If I made an OSX app, is there a way I could run this command and then print out the result to the Xcode console?

例如,如果我想列出mac终端中的所有文件,我会使用'ls'。如果我制作了一个OSX应用程序,有没有办法可以运行这个命令,然后将结果打印到Xcode控制台?

I'm assuming this exists because it seems like something that should exist and with all the utilities on the App Store I'm sure some of them perform terminal commands.

我假设这是存在的,因为它似乎应该存在的东西和App Store上的所有实用程序我相信它们中的一些执行终端命令。

Anyway, on short, how can I run terminal commands from an OSX app

无论如何,总之,我如何从OSX应用程序运行终端命令

Answers preferably in Swift but I can translate fairly well from Objective-C.

答案最好在Swift中,但我可以从Objective-C中很好地翻译。

Thanks!

谢谢!

1 个解决方案

#1


0  

What you need is a NSTask

你需要的是一个NSTask

This is the doc And this is just an example of execution

这是doc而这只是执行的一个例子

    NSString *path = @"/usr/local/bin/gls";
    NSArray *args = @[@"-l", @"-a", @"-F"];
    NSTask *task = [NSTask launchedTaskWithLaunchPath:path arguments:args];
    [task waitUntilExit];

If you also need to use the output of the command line tool you need to use NSPipe and you can find a nice tutorial here

如果您还需要使用命令行工具的输出,则需要使用NSPipe,您可以在此处找到一个很好的教程

#1


0  

What you need is a NSTask

你需要的是一个NSTask

This is the doc And this is just an example of execution

这是doc而这只是执行的一个例子

    NSString *path = @"/usr/local/bin/gls";
    NSArray *args = @[@"-l", @"-a", @"-F"];
    NSTask *task = [NSTask launchedTaskWithLaunchPath:path arguments:args];
    [task waitUntilExit];

If you also need to use the output of the command line tool you need to use NSPipe and you can find a nice tutorial here

如果您还需要使用命令行工具的输出,则需要使用NSPipe,您可以在此处找到一个很好的教程