gpt4 book ai didi

python - NSPipe - 如何将返回的数据转换为 NSArray

转载 作者:行者123 更新时间:2023-12-01 05:56:53 25 4
gpt4 key购买 nike

我的应用程序使用 NSTask 启动 Python 脚本,然后该脚本通过 NSPipe 返回一个数组。我读取数据,将其粘贴在字符串中,然后显示它:

NSMutableData *data = [[NSMutableData alloc] init];
NSData *readData;

while ((readData = [readHandle availableData])&& [readData length]) {
[data appendData: readData];
}


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

这一切都很好,但我意识到我确实需要将其保留为数组 - 而不是字符串。我找不到从数据(从 NSPipe 返回的数据)启动数组的方法。我怎样才能做到这一点?我发现的最接近的东西可能是使用:

[NSPropertyListSerialization dataWithPropertyList:format:options:error:]

...但我本身不需要“属性列表”。我必须先将数据转换为 plist 吗?

编辑:我刚刚意识到它比我想象的更复杂。 Python返回一个字典数组,字典中有字符串。这些字符串可以有逗号和其他字符,所以我认为我不能使用“,”分隔符来分隔它。

在Python中:

msg_set = []
msg_set = [
dict(mts="t,s1", mfrom="f@ro,m1", msbj="msb,j1", mbody="bod,y1", mid="i,d1"),
dict(mts="ts2", mfrom="from2", msbj="msb,j2", mbody="body2", mid="id2")
]
print msg_set # <- this is what python returns

最佳答案

你可以先将数据转换为JSON(我看到了dasblinkenlight答案的评论,但我已经输入了我的答案),然后将它们传递给Cocoa。像这样的事情:

Python端

import json
#...
json.dumps(msg_set) # <- return this one instead

Objective-C 方面

NSString *myPythonJson = @""; // <- Whatever you got from python
NSError *error = nil;
id myObjectsFromJson = [NSJSONSerialization JSONObjectWithData:[myPythonJson dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];

关于python - NSPipe - 如何将返回的数据转换为 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12057620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com