【问题标题】:NSTask launch path not accessible. Works in Xcode. Error shown out of XCodeNSTask 启动路径不可访问。在 Xcode 中工作。 XCode 显示错误
【发布时间】:2013-06-24 19:15:10
【问题描述】:

好的。关于堆栈溢出有几个问题。 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);

此代码设置两个读取管道并运行一个命令:which git

如果我在 XCode 中运行它,我会得到正确的结果:

Error value: ""  
Output Value: /usr/bin/git

如果我转到我的 build/Products/Debug 文件夹并双击可执行文件,我会在控制台应用程序上打印此消息:

问题:那么,这里真正的问题是什么?请不要提出替代解决方案...我也想知道问题是什么...谢谢。

【问题讨论】:

    标签: objective-c cocoa nstask


    【解决方案1】:

    好的,原来答案是堆栈溢出,但它分布在不同的问题上。

    问题是在这里提出的 -> 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 environmentFind out location of an executable file in Cocoa 这两个答案之后,我才意识到解决方案。

    看起来这是关于设置任一 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];
    

    但是,这假设用户的 shell 总是 bash,其他人会失败。通过确定shell来解决这个问题。

    NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];
    NSString *shellString = [environmentDict objectForKey:@"SHELL"];
    

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多