Execute a terminal command from a Cocoa app

Source: Internet
Author: User

Http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app

In the spirit of sharing ... this was 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 the script is read and run at R Untime. 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 ize simple Things (like which host to rsync ...) without re-compiling the application, but just editing the shell script In the bundle.

//-------------------------------------------------------(void)RunScript:(NSString*)ScriptName{ Nstask *Task;Task= [[NstaskAlloc]Init]; [Task Setlaunchpath: @"/bin/sh"]; Nsarray *Arguments; NSString*NewPath= [NSStringstringWithFormat:@"%@/%@",[[NSBundleMainbundle]Privateframeworkspath],ScriptName]; NSLog(@"Shell script path:%@",NewPath);Arguments= [NsarrayArraywithobjects:NewPath,Nil]; [Task Setarguments:Arguments]; Nspipe *Pipe;Pipe= [NspipePipe]; [Task Setstandardoutput:Pipe]; Nsfilehandle *File;File= [Pipe filehandleforreading]; [Task launch]; NSData *Data;Data= [File Readdatatoendoffile nsstring *string string = [[nsstring< Span class= "PLN" > Alloc] Initwithdata:: Nsutf8stringencoding]; Span class= "Typ" >nslog  (@ "script returned:\n%@" , String}//------------------------------------------------------  

Execute a terminal command from a Cocoa app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.