Quickstart: Use Python API to run an Azure Batch job

Get started with Azure Batch by using the Python API to run an Azure Batch job from an app. The app uploads input data files to Azure Storage and creates a pool of Batch compute nodes (virtual machines). It then creates a job that runs tasks to process each input file in the pool using a basic command.

After completing this quickstart, you'll understand key concepts of the Batch service and be ready to try Batch with more realistic workloads at larger scale.

Overview of the Azure Batch workflow


  • An Azure account with an active subscription. Create an account for free.

  • A Batch account and a linked Azure Storage account. To create these accounts, see the Batch quickstarts using the Azure portal or Azure CLI.

  • Python version 3.6 or later, including the pip package manager.

Sign in to Azure

Sign in to the Azure portal at https://portal.azure.com.

Get account credentials

For this example, you need to provide credentials for your Batch and Storage accounts. A straightforward way to get the necessary credentials is in the Azure portal. (You can also get these credentials using the Azure APIs or command-line tools.)

  1. Select All services > Batch accounts, and then select the name of your Batch account.

  2. To see the Batch credentials, select Keys. Copy the values of Batch account, URL, and Primary access key to a text editor.

  3. To see the Storage account name and keys, select Storage account. Copy the values of Storage account name and Key1 to a text editor.

Download the sample

Download or clone the sample app from GitHub. To clone the sample app repo with a Git client, use the following command:

git clone https://github.com/Azure-Samples/batch-python-quickstart.git

Go to the directory that contains the Python script python_quickstart_client.py.

In your Python development environment, install the required packages using pip.

pip install -r requirements.txt

Open the file config.py. Update the Batch and storage account credential strings with the values you obtained for your accounts. For example:

BATCH_ACCOUNT_NAME = 'mybatchaccount'
BATCH_ACCOUNT_KEY = 'xxxxxxxxxxxxxxxxE+yXrRvJAqT9BlXwwo1CwF+SwAYOxxxxxxxxxxxxxxxx43pXi/gdiATkvbpLRl3x14pcEQ=='
BATCH_ACCOUNT_URL = 'https://mybatchaccount.mybatchregion.batch.azure.com'
STORAGE_ACCOUNT_NAME = 'mystorageaccount'
STORAGE_ACCOUNT_KEY = 'xxxxxxxxxxxxxxxxy4/xxxxxxxxxxxxxxxxfwpbIC5aAWA8wDu+AFXZB827Mt9lybZB1nUcQbQiUrkPtilK5BQ=='

Run the app

To see the Batch workflow in action, run the script:

python python_quickstart_client.py

After running the script, review the code to learn what each part of the application does.

When you run the sample application, the console output is similar to the following. During execution, you experience a pause at Monitoring all tasks for 'Completed' state, timeout in 00:30:00... while the pool's compute nodes are started. Tasks are queued to run as soon as the first compute node is running. Go to your Batch account in the Azure portal to monitor the pool, compute nodes, job, and tasks in your Batch account.

Sample start: 11/26/2018 4:02:54 PM

Uploading file taskdata0.txt to container [input]...
Uploading file taskdata1.txt to container [input]...
Uploading file taskdata2.txt to container [input]...
Creating pool [PythonQuickstartPool]...
Creating job [PythonQuickstartJob]...
Adding 3 tasks to job [PythonQuickstartJob]...
Monitoring all tasks for 'Completed' state, timeout in 00:30:00...

After tasks complete, you see output similar to the following for each task:

Printing task output...
Task: Task0
Node: tvm-2850684224_3-20171205t000401z
Standard output:
Batch processing began with mainframe computers and punch cards. Today it still plays a central role in business, engineering, science, and other pursuits that require running lots of automated tasks....

Typical execution time is approximately 3 minutes when you run the application in its default configuration. Initial pool setup takes the most time.

Review the code

The Python app in this quickstart does the following:

  • Uploads three small text files to a blob container in your Azure storage account. These files are inputs for processing by Batch tasks.
  • Creates a pool of two compute nodes running Ubuntu 20.04 LTS.
  • Creates a job and three tasks to run on the nodes. Each task processes one of the input files using a Bash shell command line.
  • Displays files returned by the tasks.

See the file python_quickstart_client.py and the following sections for details.


To interact with a storage account, the app creates a BlobServiceClient object.

blob_service_client = BlobServiceClient(

The app uses the blob_service_client reference to create a container in the storage account and to upload data files to the container. The files in storage are defined as Batch ResourceFile objects that Batch can later download to compute nodes.

input_file_paths = [os.path.join(sys.path[0], 'taskdata0.txt'),
                    os.path.join(sys.path[0], 'taskdata1.txt'),
                    os.path.join(sys.path[0], 'taskdata2.txt')]

input_files = [
    upload_file_to_container(blob_service_client, input_container_name, file_path)
    for file_path in input_file_paths]

The app creates a BatchServiceClient object to create and manage pools, jobs, and tasks in the Batch service. The Batch client in the sample uses shared key authentication. Batch also supports Azure Active Directory authentication.

credentials = SharedKeyCredentials(config.BATCH_ACCOUNT_NAME,

    batch_client = BatchServiceClient(

Create a pool of compute nodes

To create a Batch pool, the app uses the PoolAddParameter class to set the number of nodes, VM size, and a pool configuration. Here, a VirtualMachineConfiguration object specifies an ImageReference to an Ubuntu Server 20.04 LTS image published in the Azure Marketplace. Batch supports a wide range of Linux and Windows Server images in the Azure Marketplace, as well as custom VM images.

The number of nodes (POOL_NODE_COUNT) and VM size (POOL_VM_SIZE) are defined constants. The sample by default creates a pool of 2 size Standard_DS1_v2 nodes. The size suggested offers a good balance of performance versus cost for this quick example.

The pool.add method submits the pool to the Batch service.

new_pool = batchmodels.PoolAddParameter(
            node_agent_sku_id="batch.node.ubuntu 20.04"),

Create a Batch job

A Batch job is a logical grouping of one or more tasks. A job includes settings common to the tasks, such as priority and the pool to run tasks on. The app uses the JobAddParameter class to create a job on your pool. The job.add method adds a job to the specified Batch account. Initially the job has no tasks.

job = batchmodels.JobAddParameter(


Create tasks

The app creates a list of task objects using the TaskAddParameter class. Each task processes an input resource_files object using a command_line parameter. In the sample, the command line runs the Bash shell cat command to display the text file. This command is a simple example for demonstration purposes. When you use Batch, the command line is where you specify your app or script. Batch provides a number of ways to deploy apps and scripts to compute nodes.

Then, the app adds tasks to the job with the task.add_collection method, which queues them to run on the compute nodes.

tasks = []

for idx, input_file in enumerate(resource_input_files):
    command = f"/bin/bash -c \"cat {input_file.file_path}\""

batch_service_client.task.add_collection(job_id, tasks)

View task output

The app monitors task state to make sure the tasks complete. Then, the app displays the stdout.txt file generated by each completed task. When the task runs successfully, the output of the task command is written to stdout.txt:

tasks = batch_service_client.task.list(job_id)

for task in tasks:

    node_id = batch_service_client.task.get(job_id, task.id).node_info.node_id
    print(f"Task: {task.id}")
    print(f"Node: {node_id}")

    stream = batch_service_client.file.get_from_task(
        job_id, task.id, config.STANDARD_OUT_FILE_NAME)

    file_text = _read_stream_as_string(

    if text_encoding is None:
        text_encoding = DEFAULT_ENCODING

    sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = text_encoding)
    sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = text_encoding)

    print("Standard output:")

Clean up resources

The app automatically deletes the storage container it creates, and gives you the option to delete the Batch pool and job. You are charged for the pool while the nodes are running, even if no jobs are scheduled. When you no longer need the pool, delete it. When you delete the pool, all task output on the nodes is deleted.

When no longer needed, delete the resource group, Batch account, and storage account. To do so in the Azure portal, select the resource group for the Batch account and select Delete resource group.

Next steps

In this quickstart, you ran a small app built using the Batch Python API to create a Batch pool and a Batch job. The job ran sample tasks, and downloaded output created on the nodes. Now that you understand the key concepts of the Batch service, you are ready to try Batch with more realistic workloads at larger scale. To learn more about Azure Batch, and walk through a parallel workload with a real-world application, continue to the Batch Python tutorial.