如何从Objective-C Cocoa应用程序执行终端命令(如grep) ?
当前回答
还有一个很好的老式POSIX系统("echo -en '\007'");
其他回答
还有一个很好的老式POSIX系统("echo -en '\007'");
in the spirit of sharing... this is a method I use frequently to run shell scripts. you can add a script to your product bundle (in the copy phase of the build) and then have the script be read and run at runtime. note: this code looks for the script in the privateFrameworks sub-path. warning: this could be a security risk for deployed products, but for our in-house development it is an easy way to customize simple things (like which host to rsync to...) without re-compiling the application, but just editing the shell script in the bundle.
//------------------------------------------------------
-(void) runScript:(NSString*)scriptName
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments;
NSString* newpath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] privateFrameworksPath], scriptName];
NSLog(@"shell script path: %@",newpath);
arguments = [NSArray arrayWithObjects:newpath, nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"script returned:\n%@", string);
}
//------------------------------------------------------
编辑:包括修复NSLog问题
如果你正在使用NSTask通过bash运行命令行实用程序,那么你需要包括这条神奇的行来保持NSLog工作:
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];
时代背景:
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];
解释在这里:http://www.cocoadev.com/index.pl?NSTask
下面是如何在Swift中做到这一点
Swift 3.0的变化: nspape已被重命名为Pipe NSTask已重命名为Process
这是基于inkit的Objective-C答案上面。他把它写成NSString -的category 对于Swift来说,它成为了String的扩展。
extension String. runascommand() ->字符串
extension String {
func runAsCommand() -> String {
let pipe = Pipe()
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", self)]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
if let result = NSString(data: file.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue) {
return result as String
}
else {
return "--- Error running command - Unable to initialize string from file data ---"
}
}
}
用法:
let input = "echo hello"
let output = input.runAsCommand()
print(output) // prints "hello"
或者是:
print("echo hello".runAsCommand()) // prints "hello"
例子:
@IBAction func toggleFinderShowAllFiles(_ sender: AnyObject) {
var newSetting = ""
let readDefaultsCommand = "defaults read com.apple.finder AppleShowAllFiles"
let oldSetting = readDefaultsCommand.runAsCommand()
// Note: the Command results are terminated with a newline character
if (oldSetting == "0\n") { newSetting = "1" }
else { newSetting = "0" }
let writeDefaultsCommand = "defaults write com.apple.finder AppleShowAllFiles \(newSetting) ; killall Finder"
_ = writeDefaultsCommand.runAsCommand()
}
注意从Pipe中读取的Process结果是一个NSString对象。它可能是一个错误字符串,也可能是一个空字符串,但它应该总是一个NSString。
因此,只要它不是nil,结果就可以转换为Swift String并返回。
如果由于某种原因,没有NSString可以从文件数据初始化,该函数返回一个错误消息。函数可以被写成返回一个可选的String?,但这将是尴尬的使用,也不会起到有用的作用,因为这种情况不太可能发生。
验尸官说:
我很惊讶没有人真正陷入阻塞/非阻塞调用问题
关于NSTask的阻塞/非阻塞调用问题,请阅读以下内容:
asynctask。m——示例代码,展示了如何实现异步stdin, stdout和stderr流处理数据与NSTask
asynctask的源代码。m可以在GitHub上找到。
fork, exec和wait应该有用,如果你不是在寻找Objective-C特定的方法。Fork创建当前运行程序的副本,exec用一个新程序替换当前运行的程序,然后wait等待子进程退出。例如(没有任何错误检查):
#include <stdlib.h>
#include <unistd.h>
pid_t p = fork();
if (p == 0) {
/* fork returns 0 in the child process. */
execl("/other/program/to/run", "/other/program/to/run", "foo", NULL);
} else {
/* fork returns the child's PID in the parent. */
int status;
wait(&status);
/* The child has exited, and status contains the way it exited. */
}
/* The child has run and exited by the time execution gets to here. */
还有一个系统,它运行命令,就像您从shell的命令行输入命令一样。这样更简单,但你对情况的控制力更弱。
我假设你正在使用一个Mac应用程序,所以这些链接指向苹果关于这些函数的文档,但它们都是POSIX,所以你应该在任何POSIX兼容的系统上使用它们。
推荐文章
- 在Mac OS X上哪里安装Android SDK ?
- Mac/OS X上的/var/lib/docker在哪里
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何在Mac OS X 10.6中使硬件发出哔哔声
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- Android Studio无法找到有效的Jvm(与MAC OS相关)
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)