通过NSTask用Cocoa执行perl脚本
发布时间:2020-12-15 21:02:51 所属栏目:大数据 来源:网络整理
导读:本文将用一个例子帮助你理解如何使用NSTask,例子通过在Cocoa中执行一个perl脚本,实现去掉给定NSString中的所有HTML标签。 ? 这里是一个简单的 perl 脚本,文件名是 stripper.pl ,功能是去掉所有 HTML 标签。 ? #!/usr/bin/perl while () { ??? $_ =~ s/ [
本文将用一个例子帮助你理解如何使用NSTask,例子通过在Cocoa中执行一个perl脚本,实现去掉给定NSString中的所有HTML标签。 ?
这里是一个简单的
perl
脚本,文件名是
stripper.pl
,功能是去掉所有
HTML
标签。
?
#!/usr/bin/perl
while (<>) {
??? $_ =~ s/<[^>]*>//gs;
print $_;
}
?
记得把这个脚本
chmod +x
,将它加入项目中,即得把它复制进执行文件包内。
?
这个方法会将
string
参数直接传递给
perl
脚本,并将结果返回。
?
- (NSString *) stringStrippedOfTags: (NSString *) string
{
??? NSBundle *bundle = [NSBundle mainBundle];
??? NSString *stripperPath;
??? stripperPath = [bundle pathForAuxiliaryExecutable: @"stripper.pl"];
???????????
??? NSTask *task = [[NSTask alloc] init];
??? [task setLaunchPath: stripperPath];
???????????
??? NSPipe *readPipe = [NSPipe pipe];
??? NSFileHandle *readHandle = [readPipe fileHandleForReading];
???????????
??? NSPipe *writePipe = [NSPipe pipe];
??? NSFileHandle *writeHandle = [writePipe fileHandleForWriting];
???????????
??? [task setStandardInput: writePipe];
??? [task setStandardOutput: readPipe];
???????????
??? [task launch];
???????????
??? [writeHandle writeData: [string dataUsingEncoding: NSASCIIStringEncoding]];
??? [writeHandle closeFile];
???????????
??? NSMutableData *data = [[NSMutableData alloc] init];
??? NSData *readData;
???????????
??? while ((readData = [readHandle availableData])
???????? ??&& [readData length]) {
??????? [data appendData: readData];
??? }
???????????
??? NSString *strippedString;
??? strippedString = [[NSString alloc]
?????????????????????????????????????????????? ?initWithData: data
?????????????????????????????????????????????? ?encoding: NSASCIIStringEncoding];
???????????
??? [task release];
??? [data release];
??? [strippedString autorelease];
???????????
??? return (strippedString);
???????????
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |