xcode NSTask和NSPipe与命令行objective-c通信的例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3208696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:31:32  来源:igfitidea点击:

NSTask and NSPipe example to comunicate with the command line objective-c

objective-cxcodeuser-interfacenstask

提问by objectiveccoder001

Can someone show a quick example on how to use NSTask and NSPipe in conjunction to do this:

有人可以展示一个关于如何结合使用 NSTask 和 NSPipe 来执行此操作的快速示例:

Charlie AI - run through terminal to comunicate with the AI

Charlie AI - 通过终端运行与 AI 通信

I want to create a nice GUI for it using xcode and objective c. I want to have 2 NSTextFields for the charlie's response and user input. Then have a send button to send the user input to the command line, then get the charlie's response and post it in the NSTextField.

我想使用 xcode 和目标 c 为它创建一个很好的 GUI。我想有 2 个 NSTextFields 用于 charlie 的响应和用户输入。然后有一个发送按钮将用户输入发送到命令行,然后获取查理的响应并将其发布到 NSTextField 中。

I can handle the GUI stuff (NSTextField, ect.) But I need help with the objective-c coding part.

我可以处理 GUI 的东西(NSTextField 等),但我需要 Objective-c 编码部分的帮助。

Thanks!

谢谢!

Elijah

以利亚

采纳答案by Nick Dowell

Apple have some nice sample code that shows how to do most of that... http://developer.apple.com/mac/library/samplecode/Moriarity/

Apple 有一些不错的示例代码,展示了如何完成大部分工作...... http://developer.apple.com/mac/library/samplecode/Moriarity/

TaskWrapper.mcontains all the clever stuff, but since you want to be able to send data to the task, you'll need to extend it a little, like so:

TaskWrapper.m包含所有聪明的东西,但是由于您希望能够将数据发送到任务,您需要对其进行一些扩展,如下所示:

[task setStandardInput: [NSPipe pipe]];

[task setStandardInput: [NSPipe pipe]];

To send input to the task, you can then do:

要将输入发送到任务,您可以执行以下操作:

[[[task standardInput] fileHandleForWriting] writeData: ...];

[[[task standardInput] fileHandleForWriting] writeData: ...];

To turn the NSTextField's value into data, you can do something like this:

要将 NSTextField 的值转换为数据,您可以执行以下操作:

NSData *data = [[inputTextField stringValue] dataUsingEncoding:NSUTF8StringEncoding];

NSData *data = [[inputTextField stringValue] dataUsingEncoding:NSUTF8StringEncoding];

...and to set the current working directory for your sub-task, use [NSTask setCurrentDirectoryPath:]

...并为您的子任务设置当前工作目录,请使用[NSTask setCurrentDirectoryPath:]

e.g.

例如

[task setCurrentDirectoryPath:@"/blah/blah"];
[task setLaunchPath:@"/blah/blah/server.sh"];

.... (other setup code)

[task launch];

回答by ceeit

There's also AMShellWrapper sample code which improves on moriarity.

还有 AMShellWrapper 示例代码,它改进了moriarity。

http://www.harmless.de/cocoa-code.php

http://www.harmless.de/cocoa-code.php