【问题标题】:Need to execute a command in Cocoa app需要在 Cocoa app 中执行命令
【发布时间】:2017-01-26 08:54:47
【问题描述】:

我正在使用 Objective-C 开发一个 macOS 应用程序,我想运行一些与终端相同的命令。实际上我想从我的应用程序中运行 YOLO 命令。我为此使用 NSTask 类。 当我通过代码运行命令时,在任务启动时,我收到错误“无法打开文件 cfg/coco.data”。 相同的命令适用于终端,但不适用于我的应用程序。

这是我的代码:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/bash"];

NSString *commandToRun = @"Desktop/darknet/ && ./darknet detect cfg/yolo.cfg   yolo.weights data/dog.jpg";

NSArray *arguments = [NSArray arrayWithObjects:
                      @"-c",
                      [NSString stringWithFormat:@"%@", commandToRun],
                      nil];
NSLog(@"run command: %@",commandToRun);
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

【问题讨论】:

标签: objective-c macos nstask


【解决方案1】:

NSTask 不是外壳。比这还低级。你不能在那里运行完整的 shell 表达式,只有一个命令。所以你的 commandToRun 没有意义,它应该只是要运行的命令的路径。

【讨论】:

    【解决方案2】:

    您可以使用system c 函数来运行命令,但它对细节没有太多控制。

    【讨论】:

      猜你喜欢
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2018-12-25
      相关资源
      最近更新 更多