【发布时间】:2009-11-29 18:33:34
【问题描述】:
我想从文件或从 Objective-C 字符串(在代码中)运行 shell 脚本。我还希望将 shell 脚本的结果存储到一个变量中。我不希望将 shell 脚本拆分为参数(例如运行时的 setLaunchPath)。例如:运行这个 shell 脚本 "mount_webdav idisk.mac.com/mac_username /Volumes/mac_username" 而不是 "/bin/mount_webdav" 然后是参数。有没有办法做到这一点?我现在正在使用 NSTask,但是当我尝试使用它时,它给我带来了一些错误。这是提出的代码:
(一些.m文件)
NSString *doshellscript(NSString *cmd_launch_path, NSString *first_cmd_pt) {
NSTask *task = [[NSTask alloc] init]; // Make a new task
[task setLaunchPath: cmd_launch_path]; // Tell which command we are running
[task setArguments: [NSArray arrayWithObjects: first_cmd_pt, nil]];
[task setArguments: first_cmd_pt];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
[task launch];
NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
[task release]; //Release the task into the world, thus destroying it.
return string;
}
NSString *mount_idisk(NSString *mac_username) {
doshellscript(@"/bin/mkdir", [@"/Volumes/" stringByAppendingString:mac_username]);
NSString *path_tmp = [mac_username stringByAppendingString: @"/ /Volumes/"];
NSString *idisk_path = [path_tmp stringByAppendingString:mac_username];
//NSLog(@"%@", [@" http://idisk.mac.com/" stringByAppendingString: idisk_path]);
NSString *finished_path = [@"http://idisk.mac.com/" stringByAppendingString: idisk_path];
doshellscript(@"/sbin/mount_webdav", finished_path);
}
...
这是我用来运行它的行:
mount_idisk("username");
【问题讨论】:
标签: objective-c shell scripting nsstring