来自应用程序的可可Objective-C Shell脚本? [英] Cocoa Objective-C shell script from application?

查看:84
本文介绍了来自应用程序的可可Objective-C Shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在创建的应用程序,并且希望在其中运行Shell脚本。其中一个脚本创建一个.plist文件,另一个脚本对二进制文件进行补丁。想要使用Shell脚本执行此操作的原因是因为我知道它可以满足我需要的两件事。我确定有一种方法可以用Objective-C / Cocoa进行,尽管我不知道该怎么做,所以任何有关如何完成此操作的建议将不胜感激

解决方案

您将需要使用 NSTask NSTask 是用于运行任何终端命令的系统。以下是使用它执行Shell脚本的方法:

  NSTask * task = [[NSTask alloc] init]; 
[任务setLaunchPath:@ / path / to / script / sh];
[任务setArguments:[NSArray arrayWithObjects:@ yourScript.sh,无]]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];

[任务启动];
[任务发布];

这将运行命令 / path / to / script / sh yourScript。 sh 。如果您的脚本需要任何参数,则可以将它们添加到参数数组中。标准输出会将所有输出重定向到管道对象,如果要输出到文件,则可以将其挂钩。我们需要使用另一个 NSPipe 进行输入的原因是为了使 NSLog 正常工作,而不是登录到脚本。 / p>

如果您想了解有关 NSTask 的工作方式的更多信息,请参见此答案


I have an application that I'm creating and would like to run a shell scripts from within it. One of the scripts creates a .plist file, and the other does a patch on a binary file. The reason why want to do this with a shell script is because I know that it works for the two things that I need it for. I'm sure there's a way to do it with Objective-C/Cocoa although I don't know how, so any recommendations on how to accomplish this would be greatly appreciated

解决方案

You'll need to use NSTask. NSTask is a system for running any Terminal command. Here's how you could use it to execute a shell script:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/script/sh"];
[task setArguments:[NSArray arrayWithObjects:@"yourScript.sh", nil]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];

[task launch];
[task release];

That would run the command /path/to/script/sh yourScript.sh. If you need any arguments for your script, you can add them to the array of arguments. The standard output will redirect all output to a pipe object, which you can hook into if you want to output to a file. The reason we need to use another NSPipe for input is to make NSLog work right instead of logging to the script.

If you want more info on how NSTask works, see this answer.

这篇关于来自应用程序的可可Objective-C Shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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