Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7158701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:06:35+00:00 2026-05-28T13:06:35+00:00

I’m trying to run a Python script from a Cocoa app. It’s working just

  • 0

I’m trying to run a Python script from a Cocoa app. It’s working just fine on the main thread, but I’d like to have it running in the background, on a concurrent GCD queue.

I’m using the following method to setup a manager class that runs the Python script:

- (BOOL)setupPythonEnvironment {
    if (Py_IsInitialized()) return YES;

    Py_SetProgramName("/usr/bin/python");
    Py_Initialize();

    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"MyScript"     ofType:@"py"];

    FILE *mainFile = fopen([scriptPath UTF8String], "r");
    return (PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]) == 0);
}

After which the script is (repeatedly) called from the following instance method, using a shared singleton instance of the manager class:

- (id)runScriptWithArguments:(NSArray *)arguments {
    return [NSClassFromString(@"MyScriptExecutor") runWithArguments:arguments];
}

The above Objective-C code hooks into the following Python code:

from Foundation import *

def run_with_arguments(arguments):
#    ...a long-running script

class MyScriptExecutor(NSObject):
    @classmethod
    def runWithArguments_(self, arguments):
        return run_with_arguments(arguments)

This works when I always run the above Objective-C methods from the main queue, but the script returns null when run from any other queue. Could someone explain me if what I’m trying to do is just not supported, and whether there’s a good way around it?

The Python scripts is called often and runs long, so doing that on the main thread would be too slow, a would be running it form a serial queue. In addition, I’d like to contain the concurrency code within Objective-C as much as possible.

Thanks,

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T13:06:36+00:00Added an answer on May 28, 2026 at 1:06 pm

    From this page, it looks like there are some some pretty complex threading concerns specific to embedding python. Is there a reason you couldn’t just run these scripts in a separate process? For instance, the following -runBunchOfScripts method would run the script ten times (by calling -runPythonScript) on a parallel background queue, collecting the resulting outputs into an array of strings, and then calling your object back on the main thread once all the scripts has completed:

    - (NSString*)runPythonScript
    {
        NSTask* task = [[[NSTask alloc] init] autorelease];
        task.launchPath = @"/usr/bin/python";  
        NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"MyScript" ofType:@"py"];
        task.arguments = [NSArray arrayWithObjects: scriptPath, nil];
    
        // NSLog breaks if we don't do this...
        [task setStandardInput: [NSPipe pipe]];
    
        NSPipe *stdOutPipe = nil;
        stdOutPipe = [NSPipe pipe];
        [task setStandardOutput:stdOutPipe];
    
        NSPipe* stdErrPipe = nil;
        stdErrPipe = [NSPipe pipe];
        [task setStandardError: stdErrPipe];
    
        [task launch];        
    
        NSData* data = [[stdOutPipe fileHandleForReading] readDataToEndOfFile];
    
        [task waitUntilExit];
    
        NSInteger exitCode = task.terminationStatus;
    
        if (exitCode != 0)
        {
            NSLog(@"Error!");
            return nil;
        }
    
        return [[[NSString alloc] initWithBytes: data.bytes length:data.length encoding: NSUTF8StringEncoding] autorelease];
    }
    
    - (void)runBunchOfScripts
    {
        dispatch_group_t group = dispatch_group_create();
        NSMutableArray* results = [[NSMutableArray alloc] init];
        for (NSUInteger i = 0; i < 10; i++)
        {
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSString* result = [self runPythonScript];
                @synchronized(results)
                {
                    [results addObject: result];
                }
            });
        }
    
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [self scriptsDidFinishWithResults: results];
            dispatch_release(group);
            [results release];
        });
    }
    
    - (void)scriptsDidFinishWithResults: (NSArray*)results
    {
        NSLog(@"Do something with the results...");
    }
    

    Naturally the approach of using separate processes has it’s limitations, not the least of which being the hard limit on the number of processes you can launch, but it seems a lot less fraught with peril than embedding the entire interpreter. I would say that unless you need to interact chattily between the scripts and the hosting environment, this would be a better approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.