objective-c – 从Cocoa应用程序执行终端命令

objective-c – 从Cocoa应用程序执行终端命令,第1张

概述如何从我的Objective-C Cocoa应用程序执行终端命令(如grep)? 你可以使用 NSTask.下面是一个运行’/ usr / bin / grep foo bar.txt’的例子。 int pid = [[NSProcessInfo processInfo] processIdentifier];NSPipe *pipe = [NSPipe pipe];NSFileHandle 如何从我的Objective-C Cocoa应用程序执行终端命令(如grep)?解决方法 你可以使用 NSTask.下面是一个运行’/ usr / bin / grep foo bar.txt’的例子。

int pID = [[nsprocessInfo processInfo] processIDentifIEr];NSPipe *pipe = [NSPipe pipe];NSfileHandle *file = pipe.fileHandleForReading;NSTask *task = [[NSTask alloc] init];task.launchPath = @"/usr/bin/grep";task.arguments = @[@"foo",@"bar.txt"];task.standardOutput = pipe;[task launch];NSData *data = [file readDataToEndOffile];[file closefile];Nsstring *grepOutput = [[Nsstring alloc] initWithData: data enCoding: NSUTF8StringEnCoding];NSLog (@"grep returned:\n%@",grepOutput);

NSPipe和NSfileHandle用于重定向任务的标准输出。

有关在Objective-C应用程序中与 *** 作系统交互的更多详细信息,您可以在Apple的开发中心:Interacting with the Operating System上查看此文档。

编辑:包括NSLog问题的修复

如果你使用NSTask通过bash运行命令行实用程序,那么你需要包括这条魔法线以保持NSLog工作:

//The magic line that keeps your log where it belongstask.standardOutput = pipe;

解释在这里:http://cocoadev.com/HowToPipeCommandsWithNSTask(< – 死链接)

总结

以上是内存溢出为你收集整理的objective-c – 从Cocoa应用程序执行终端命令全部内容,希望文章能够帮你解决objective-c – 从Cocoa应用程序执行终端命令所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1050633.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存