我不知道为什么这个方法返回一个空字符串:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
如果不是@"git"作为参数传递,我传递@"which"我/usr/bin/which按预期返回.所以至少原理是有效的.
从终端
$ which which
$ /usr/bin/which
$
$ which git
$ /usr/local/git/bin/git
Run Code Online (Sandbox Code Playgroud)
所以它在那里工作. …
我在我的Cocoa项目中使用以下代码来调用我创建的脚本.该脚本与项目位于同一文件夹中,甚至显示在XCode的"Resources"文件夹下.找到了正确的路径,但仍然说路径无法访问.请帮忙.
NSBundle *mainBundle=[NSBundle mainBundle];
NSString *path=[mainBundle pathForResource:@"script" ofType:@"sh"];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: path];
NSLog (path);
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
[task setStandardError: pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
[task waitUntilExit];
NSData *data = [ddFile readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
HDSpeed = [f output];
[f release];
[task release];
Run Code Online (Sandbox Code Playgroud)
我在调试器中得到的输出是:
2010-07-10 17:53:26.384 tester[5023:a0f] /Users/guest/Library/Developer/Xcode/DerivedData/tester-bhukztmqjwoqrwereagsshvtbfqx/Build/Products/Debug/tester.app/Contents/Resources/script.sh
2010-07-10 17:53:26.386 tester[5023:a0f] launch path not …
简单的问题是:如何在Cocoa应用程序中找出可执行文件的位置.
请记住,在许多类Unix操作系统中,人们使用PATH环境为其可执行文件分配首选位置,尤其是当他们的系统中有多个版本的相同应用程序时.作为一个好习惯,我们的Cocoa应用程序应该找到它需要的可执行文件的PREFERRED位置.
例如,/ usr/bin中的Leopard默认配置中有一个SVN 1.4,你通过/ opt/local/bin上的MacPorts安装了一个更新的版本,比如SVN 1.5.3.你可以使用/etc/path.d或.bash_profile或.zshrc设置你的PATH:
export PATH =/opt/local/bin:$ PATH
因此,您可以使用新版本的svn而不是系统中的旧版本.它适用于任何终端环境.但不是在Cocoa应用程序中.据我所知,Cocoa应用程序只有一个默认的PATH环境,如下所示:
export PATH ="/ usr/bin:/ bin:/ usr/sbin:/ sbin"
默认情况下,它不会使用/etc/path.d,.bash_profile,.profile,.zshrc等中的配置.
那我们究竟怎么办?