NSTask没有从用户的环境中获取$ PATH

时间:2008-12-22 17:18:24

标签: objective-c cocoa bash shell nstask

我不知道为什么这个方法返回一个空字符串:

- (NSString *)installedGitLocation {
    NSString *launchPath = @"/usr/bin/which";

    // Set up the task
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:launchPath];
    NSArray *args = [NSArray arrayWithObject:@"git"];
    [task setArguments:args];

    // Set the output pipe.
    NSPipe *outPipe = [[NSPipe alloc] init];
    [task setStandardOutput:outPipe];

    [task launch];

    NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile];
    NSString *path = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    return path;
}

如果不是传递@"git"作为参数,而是传递@"which"我按预期返回/usr/bin/which。所以至少原则是有效的。

来自终端

$ which which
$ /usr/bin/which
$
$ which git
$ /usr/local/git/bin/git

所以它在那里工作。

我唯一能想到的是which没有搜索我环境中的所有路径。

这让我抓狂!有没有人有任何想法?

编辑:看起来这是关于设置NSTask或用户的shell(例如〜/ .bashrc),以便NSTask看到正确的环境($ PATH)。

5 个答案:

答案 0 :(得分:19)

尝试,

    [task setLaunchPath:@"/bin/bash"];
    NSArray *args = [NSArray arrayWithObjects:@"-l",
                     @"-c",
                     @"which git",
                     nil];
    [task setArguments: args];

这对雪豹有用;我没有在任何其他系统上测试过。 -l(小写L)告诉bash“就像它已被调用为登录shell一样”,并且在此过程中它获取了我正常的$ PATH。如果启动路径设置为/ bit / sh,即使使用-l。

,这对我也无效

答案 1 :(得分:12)

通过NSTask运行任务使用fork()exec()来实际运行任务。用户的交互式shell根本不涉及。由于$PATH(基本上)是一个shell概念,所以当你谈论以其他方式运行进程时,它不适用。

答案 2 :(得分:2)

运行程序时$ PATH中是/ usr / local / git / bin吗?我认为which只能查看用户的$ PATH。

答案 3 :(得分:1)

查看问题Find out location of an executable file in Cocoa。看起来基本问题是一样的。不幸的是,答案并不好听,但有一些有用的信息。

答案 4 :(得分:0)

在Swift NSTask中被Process代替,但这对我有用:

let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-l", "-c", "which git"]
相关问题