Skip to content

Instantly share code, notes, and snippets.

@cschamp
Created May 13, 2009 14:14
Show Gist options
  • Save cschamp/111040 to your computer and use it in GitHub Desktop.
Save cschamp/111040 to your computer and use it in GitHub Desktop.
// Demonstrates how to pipe a program from memory to Python interpreter.
// Adapted from http://borkware.com/quickies/one?topic=NSTask
#import <Foundation/Foundation.h>
static const char *prog = "print \"Hello, world!\";";
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/python"];
NSPipe *readPipe = [NSPipe pipe];
NSFileHandle *readHandle = [readPipe fileHandleForReading];
NSPipe *writePipe = [NSPipe pipe];
NSFileHandle *writeHandle = [writePipe fileHandleForWriting];
[task setStandardInput:writePipe];
[task setStandardOutput:readPipe];
[task launch];
NSData *progdata = [[NSData alloc] initWithBytes:(const void *)prog length:strlen(prog)];
[writeHandle writeData:progdata];
[writeHandle closeFile];
NSMutableData *data = [[NSMutableData alloc] init];
NSData *readData;
while ((readData = [readHandle availableData]) && [readData length]) {
[data appendData:readData];
}
NSString *resultString;
resultString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(resultString);
[task release];
[data release];
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment