好的。关于堆栈溢出有几个与此相关的问题。这是唯一的问题 https://stackoverflow.com/questions/8254680/nstask-only-returning-standarderror-in-release-build最接近地雷,但它使用通知。
代码非常简单。创建一个新的空 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);
此代码设置两个读取管道并运行一个命令:which git
.
如果我在 XCode 中运行它,我会正确得到以下结果:
Error value: ""
Output Value: /usr/bin/git
如果我转到 build/Products/Debug 文件夹并双击可执行文件,我会在控制台应用程序上打印以下消息:
问题:那么,这里真正的问题是什么?请不要提出替代解决方案...我也想知道问题是什么..谢谢。
好吧,事实证明答案是堆栈溢出,但它分布在不同的问题中。
问题在这里提出 ->NSTask 的命令 https://stackoverflow.com/questions/10965007/commands-with-nstask在这里 ->NSTask 启动路径不可访问 https://stackoverflow.com/questions/3221432/nstask-launch-path-not-accessible还有
但截至目前,他们的答案尚不清楚问题所在。只有在阅读了问题之后NSTask 未从用户环境中获取 $PATH https://stackoverflow.com/questions/386783/nstask-not-picking-up-path-from-the-users-environment(问题的标题具有误导性)并且有这两个答案NSTask 未从用户环境中获取 $PATH https://stackoverflow.com/questions/386783/nstask-not-picking-up-path-from-the-users-environment/1817870#1817870 and 找出 Cocoa 中可执行文件的位置 https://stackoverflow.com/questions/208897/find-out-location-of-an-executable-file-in-cocoa/387809#387809我意识到了解决方案。
看起来这是关于设置 NS
任务或用户的 shell(例如 ~/.bashrc)以便正确
NSTask 可以看到环境($PATH)。
解决方案:
[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];
然而,这假设用户的外壳是alwaysbash 对于其他人来说它会失败。通过确定外壳来解决这个问题。
NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];
NSString *shellString = [environmentDict objectForKey:@"SHELL"];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)