Scripting Bacalhau with Python
Bacalhau allows you to easily execute batch jobs via the CLI. But sometimes you need to do more than that. You might need to execute a script that requires user input, or you might need to execute a script that requires a lot of parameters. In any case, you probably want to execute your jobs in a repeatable manner.
This example demonstrates a simple Python script that is able to orchestrate the execution of lots of jobs in a repeatable manner.
Prerequisite
To get started, you need to install the Bacalhau client, see more information here
Executing Bacalhau Jobs with Python Scripts
To demonstrate this example, I will use the data generated from an Ethereum example. This produced a list of hashes that I will iterate over and execute a job for each one.
Now let's create a file called bacalhau.py
. The script below automates the submission, monitoring, and retrieval of results for multiple Bacalhau jobs in parallel. It is designed to be used in a scenario where there are multiple hash files, each representing a job, and the script manages the execution of these jobs using Bacalhau commands.
This code has a few interesting features:
Change the value in the
main
call (main("hashes.txt", 10)
) to change the number of jobs to execute.Because all jobs are complete at different times, there's a loop to check that all jobs have been completed before downloading the results. If you don't do this, you'll likely see an error when trying to download the results. The
while True
loop is used to monitor the status of jobs and wait for them to complete.When downloading the results, the IPFS get often times out, so I wrapped that in a loop. The
for i in range(0, 5)
loop in thegetResultsFromJob
function involves retrying thebacalhau job get
operation if it fails to complete successfully.
Let's run it!
Hopefully, the results
directory contains all the combined results from the jobs we just executed. Here's we're expecting to see CSV files:
Success! We've now executed a bunch of jobs in parallel using Python. This is a great way to execute lots of jobs in a repeatable manner. You can alter the file above for your purposes.
Next Steps
You might also be interested in the following examples:
Analysing Data with Python Pandas
Support
If you have questions or need support or guidance, please reach out to the Bacalhau team via Slack (#general channel).
Last updated