Created
May 13, 2009 14:14
-
-
Save cschamp/111040 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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