[Python] How do I run a background process and get the returned data in a python FastAPI HTTP...

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am using python FastAPI to run a GET request which runs a .jar file that returns some text. The GET request is triggered by a button press on the front-end. The java program takes about 30 seconds to complete and I have attempted to run it asynchronously, but have been unable to. Pressing the button twice one second apart keeps taking 60 seconds rather than 31

    I have tried to use threading module (though this I believe won't allow me to get the returned data), but even that makes me wait for the process to finish before it starts the next one.

    I'm not sure how to modify the code below to be able to call the subprocess.run() function asynchronously (or using a different function to execute the java command would be fine too).

    async def test_java():
    print(f'Starting: {datetime.now()}')
    try:
    msg = subprocess.run(['java', '-cp', 'AsyncTest.jar', 'AsyncTest'], cwd='java_files', capture_output=True, check=True, text=True)
    results = msg.stdout if msg.stdout else msg.stderr
    except:
    return JSONResponse(
    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
    content={
    'results': f'error running script'
    }
    )

    print(f'Finishing: {datetime.now()}')

    return JSONResponse(
    status_code=status.HTTP_200_OK,
    content={
    'results': results
    }
    )

    Continue reading...

Compartilhe esta Página