Running a simple Python script from inside your app (OS X/Xcode)


Step 1

The first requirement is a python script, so go ahead and create this in your favourite text editor:

#!/usr/bin/python

print "Hello World!"

The path to the python installation is important here and must be included.

Step 2

Next you need to set the permissions so that Xcode will be able to run the file at run time. We do this by opening Terminal and entering the following command:

chmod 777 hello.py

Note: Either you need to be in the directory where the file was saved to do this or you need to include the full file path where I have hello.py.

Step 3

You are now ready to drag the file into an OS X project. And once you've done this add the following code to your AppDelegate file:

- (void)runPythonScript {
   
NSTask *task = [[NSTask alloc] init];
     
        // file must be made executable using chmod 777 in Terminal
NSString *pythonFile = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"py"];
[task setLaunchPath:pythonFile];
 
[task setStandardInput:[NSPipe pipe]];
[task setStandardOutput:[NSPipe pipe]];
   
[task launch];
[task waitUntilExit];
 
NSData *outputData = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile];
NSString *resultString = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
 
        NSLog(@"%@",resultString);
 
}

cf. NSTask and NSPipe in Apple's documentation and see also the sources at the foot of this post.

Step 4

To run simply place

[self runPythonScript];

Within the applicationDidFinishLaunching: method.

Sources

MacDown - GitHub

'How do you CHMOD on OS X?' - MacRumors Forum


Endorse on Coderwall

Comments

  1. Him this is exactly what I need, but would like to do it in swift, can you help me with that ?

    ReplyDelete
    Replies
    1. For now, see here -https://twitter.com/sketchyTech/status/599976936874606593/photo/1 - I'll update post with code soon-ish

      Delete

Post a Comment