objective-c – 无法访问NSTask启动路径.适用于Xcode. XCode显示
好.关于堆栈溢出有几个问题.
This question was the only question最接近地雷,但它使用通知.
代码非常简单.创建一个新的空Mac OSX项目,然后将以下代码粘贴到applicationDidFinishLaunching:方法中.它应该获取任何可执行文件的路径(在本例中为GIT). NSTask *aTask = [[NSTask alloc] init]; NSPipe *outputPipe = [NSPipe pipe]; NSPipe *errorPipe = [NSPipe pipe]; [aTask setStandardOutput: outputPipe]; [aTask setStandardError: errorPipe]; [aTask setArguments:[NSArray arrayWithObject:@"which"]]; [aTask setLaunchPath:@"/usr/bin/git"]; NSFileHandle *outputFileHandler = [outputPipe fileHandleForReading]; NSFileHandle *errorFileHandler = [errorPipe fileHandleForReading]; [aTask launch]; [aTask waitUntilExit]; // Task launched now just read and print the data NSData *data = [outputFileHandler readDataToEndOfFile]; NSString *outPutValue = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSData *errorData = [errorFileHandler readDataToEndOfFile]; NSString *errorValue = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding]; NSLog(@"Error value: %@",errorValue); NSLog(@"Output Value: %@",outPutValue); 这段代码设置了两个读取管道并运行一个命令:git. 如果我在XCode中运行它,我会得到相应的结果: Error value: "" Output Value: /usr/bin/git 如果我转到我的build / Products / Debug文件夹并双击可执行文件,我会在控制台应用程序上打印此消息: 问:那么,这里的问题到底是什么?请不要做出替代解决方案……我也想知道问题是什么..谢谢. 解决方法
好的结果是答案是关于堆栈溢出,但它分散在不同的问题上.
这里问的问题是 – > Commands with NSTask和这里 – > NSTask launch path not accessible也是 但截至目前为止,他们的回答并不清楚问题所在.只有在阅读了NSTask not picking up $PATH from the user’s environment的问题之后(问题标题具有误导性),并且通过这两个答案NSTask not picking up $PATH from the user’s environment和Find out location of an executable file in Cocoa我才意识到解决方案.
解: [task setLaunchPath:@"/bin/bash"]; NSArray *args = [NSArray arrayWithObjects:@"-l",@"-c",@"which git",//Assuming git is the launch path you want to run nil]; [task setArguments: args]; 但是,这假设用户的shell始终是bash,而其他人则会失败.通过确定shell来解决这个问题. NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment]; NSString *shellString = [environmentDict objectForKey:@"SHELL"]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |