简体   繁体   English

需要在可可应用中执行命令

[英]Need to execute a command in Cocoa app

I am developing a macOS app using Objective-C that I want to run some commands same like terminal. 我正在使用Objective-C开发一个macOS应用,我想运行一些与终端相同的命令。 Actually I want to run YOLO command from my application. 实际上,我想从我的应用程序中运行YOLO命令。 I am using NSTask class for this. 我为此使用NSTask类。 When I run the command through code, on task launch, I am getting error "Couldn't open file cfg/coco.data". 当我通过代码运行命令时,在任务启动时,出现错误“无法打开文件cfg / coco.data”。 The same command works fine with terminal but not in my application. 相同的命令可以在终端上正常工作,但不能在我的应用程序中使用。

Here is my code: 这是我的代码:

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];

NSTask is not a shell. NSTask不是shell。 It's more low-level than that. 它比这更底层。 You can't run full shell expressions in there, just one command. 您不能在其中运行完整的shell表达式,只能执行一个命令。 So your commandToRun makes no sense, it should only be the path to the command to run. 因此,您的commandToRun没有意义,它应该仅是要运行的命令的路径。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM