使用Python Boto3调用AWS Translate的StartTextTranslationJob后,如何判断任务完成及查询状态
Hey there! I’ve worked with AWS Translate and Boto3 quite a bit, so let’s break down exactly how to check if your translation job is done and retrieve its status. Here’s a step-by-step guide with code examples you can use right away:
First: Grab the Job ID
When you call start_text_translation_job(), the API response includes a unique JobId—you’ll need this to track the job later. Store it somewhere (like a variable or database) right after starting the job:
import boto3 # Initialize the Translate client (make sure to set your region) translate_client = boto3.client('translate', region_name='us-east-1') # Start your translation job job_response = translate_client.start_text_translation_job( InputDataConfig={ 'S3Uri': 's3://your-input-bucket/input-files/', 'ContentType': 'text/plain' }, OutputDataConfig={ 'S3Uri': 's3://your-output-bucket/results/' }, SourceLanguageCode='en', TargetLanguageCodes=['fr', 'de'], DataAccessRoleArn='arn:aws:iam::123456789012:role/translate-access-role' ) # Save the job ID for status checks job_id = job_response['JobId'] print(f"Started translation job with ID: {job_id}")
Second: Query the Job Status
Use the describe_text_translation_job() method to pull the current status of your job. This API returns all key details about the job, including its progress, errors (if any), and final status.
Here’s a reusable function to get the status:
def get_translate_job_status(job_id): status_response = translate_client.describe_text_translation_job(JobId=job_id) job_properties = status_response['TextTranslationJobProperties'] current_status = job_properties['JobStatus'] print(f"Current job status: *{current_status}*") # Optional: Print progress percentage if available if 'JobProgress' in job_properties: progress = job_properties['JobProgress']['PercentComplete'] print(f"Job progress: {progress}%") # If the job failed, print the error message if current_status == 'FAILED' and 'Message' in job_properties: print(f"Failed reason: {job_properties['Message']}") return current_status
Third: Wait for the Job to Finish (Polling)
Since translation jobs run asynchronously, you’ll want to set up a simple polling loop to wait until the job completes, fails, or gets stopped. Just make sure to add a delay between checks to avoid hitting AWS API rate limits.
Example polling function:
import time def wait_for_job_completion(job_id, check_interval=30): """Wait for the translation job to finish, checking status every X seconds.""" while True: status = get_translate_job_status(job_id) # Exit loop when the job reaches a terminal state if status in ['COMPLETED', 'FAILED', 'STOPPED']: print(f"\nJob finished with status: *{status}*") break print(f"Job still running. Checking again in {check_interval} seconds...\n") time.sleep(check_interval) # Call the function to wait for your job wait_for_job_completion(job_id)
Key Status Values to Know
Let’s clarify what each status means:
SUBMITTED: The job has been sent to AWS but hasn’t started processing yetIN_PROGRESS: The job is actively running in the cloudCOMPLETED: Success! Your translated files are ready in the specified S3 output bucketFAILED: The job didn’t finish—check theMessagefield for details (common issues: bad S3 permissions, invalid language codes)STOPPED: The job was manually halted before completion
Quick Notes
- Make sure your IAM role has the
translate:DescribeTextTranslationJobpermission—otherwise you’ll get an access denied error - Don’t set the polling interval too short (stick to 10-30 seconds minimum) to avoid throttling
- If the job fails, double-check your S3 paths, language codes, and IAM role permissions first—those are the most common culprits
内容的提问来源于stack exchange,提问作者lotus airtel300

