简体   繁体   中英

Cocoa application - NSTask

How can I programmatically run terminal command?

Now I'm doing like this:

-(IBAction)proceedTapped:(id)sender
{
NSLog(@"%@",[self runCommand:@"cd ~"]);
NSLog(@"%@",[self runCommand:@"ls"]);
}

-(NSString *)runCommand:(NSString *)commandToRun
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
                      @"-c" ,
                      [NSString stringWithFormat:@"%@", commandToRun],
                      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 *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}

For single commands this code works well, but in my case, when I want to change directory to ~(home) and then do 'ls' this doesn't work well (it looks like to run two commands in two different terminal windows). So how to run multiple commands like in one terminal window ? Thank you.

In one of my applications I have:-

- (IBAction)openDirInTerminal:(id)sender {  // context only
    DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem];
    NSString *s = [NSString stringWithFormat:
                   @"tell application \"Terminal\" to do script \"cd \'%@\'\"", item.fullPath];
    NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
    [as executeAndReturnError:nil];
}

DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem]; is my method, but replace item.fullPath with a Path.

You could add the 2nd command to the script string (followed by a newline).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM