How to write your own Robot Framework libraries in Python
Quick recap on libraries and keywords
Robot Framework works in a modular way: you can easily add more Keywords to your robots by adding Libraries. Robot Framework includes a set of standard libraries, and you can get more libraries installing additional packages.
For example, by adding the rpaframework package, you get all the keywords included in it.
Once you have added a Library to your script, you can use the Keywords that the library includes. For example, in this script, we are adding the RPA.Browser
library, and we are using the Open Available Browser
and Capture Page Screenshot
keywords that it provides:
*** Settings ***
Documentation A simple example of using a library.
Library RPA.Browser
*** Tasks ***
Take a screenshot of the Robocorp frontpage
Open Available Browser https://www.robocorp.com
Capture Page Screenshot
Sometimes your use case might have some specific requirements that you feel cannot be achieved with readily available libraries. Or, you might be more comfortable coding in a "lower level" language than Robot Framework. If that's the case, a great way to still get all the benefits of Robot Framework (and the Robocorp ecosystem) but get more control over the code is to add your custom libraries and keywords using Python!
Custom library examples
These examples use the default robot structure in Robocorp Lab.
The simplest custom library: a single Python function
In our example use case, based on RobotSpareBin Industries Inc., our favorite fictional company, we have some sales representatives that have a weekly sales goal. We want to show a feedback message to each sales representative based on their actual sales results for the week as part of a software robot.
Sounds like an interesting use case? It happens to be the story of our Beginners' course. Go and take it if you haven't already!
The feedback message depends on a bit of calculation, so we decide that the best approach for us is to have the logic in a custom library, which we decide to call PerformanceFeedback
. So:
- We add a file called
PerformanceFeedback.py
in the root of our package. - We add this code to it:
def get_sales_performance_feedback(sales_result, sales_target):
ratio = int(sales_result) / int(sales_target)
if ratio >= 1:
return "A great result!"
elif ratio > 0.75:
return "You did not quite make it, but not too bad."
elif ratio >= 0.5:
return "Well, at least you tried"
else:
return "The boss wants to see you..."
NOTE: you can also decide to create a different directory in your package for your library, and put your library Python file there. For this to work, you will need to add the subdirectory to the
PYTHONPATH
section of yourrobot.yaml
file.
This function expects two arguments: the actual sales result for the week and a sales target, which is different for each sales representative. We make sure that the function is operating on numbers, then we compare the sales result and the sales target, and we return a feedback message.
- Now we can import and use the library in our
.robot
file, like in this simple example:
*** Settings ***
Documentation Example robot to show the use of a custom library.
Library PerformanceFeedback
*** Variables ***
&{sales_rep_nathan}= salesResult=502 salesTarget=1000
&{sales_rep_pamela}= salesResult=112 salesTarget=100
*** Tasks ***
Calculate the performance for some example sales reps
${performance_nathan}= Get Sales Performance Feedback
... ${sales_rep_nathan}[salesResult]
... ${sales_rep_nathan}[salesTarget]
${performance_pamela}= Get Sales Performance Feedback
... ${sales_rep_pamela}[salesResult]
... ${sales_rep_pamela}[salesTarget]
- We added the name of the library in the
*** Settings ***
section. - Our library contains a function called
get_sales_performance_feedback
: this gives us a keyword calledGet Sales Performance Feedback
. - The
Get Sales Performance Feedback
keyword requires two arguments like the function that it comes from, so we can call it with the sales results and targets for our two hypothetical sales representatives.
Executing our robot will now produce this log output:
We now have a basic Python library that we can use in our robot script. We can add as many new functions to the library as we need, and use them as keywords.
Use a class as your custom library
You can also organize the code in your library in a class. In this case, the class and the filename of the library have to match, and the class methods become available as keywords.
As an example, to get a keyword called Get Current Date
, you could add this code in a file called ExampleLibrary.py
:
from datetime import date
class ExampleLibrary:
def get_current_date(self):
return date.today()
Remember: the file name and the class name must match, otherwise your library won't work! 🤯
Using rpaframework
in your custom Python library
Having your custom library does not mean that you have to code everything from scratch. In fact, it is very easy to import other libraries and packages and integrate them into your code. For example, you can use the RPA Framework both in Robot Framework and in Python directly.
As an example, consider the Orders
library that we created as part of the Web store order robot:
from RPA.Excel.Files import Files
from RPA.Tables import Tables
class Orders:
def get_orders(self, excel):
files = Files()
workbook = files.open_workbook(excel)
rows = workbook.read_worksheet(header=True)
tables = Tables()
table = tables.create_table(rows)
tables.filter_empty_rows(table)
orders = []
for row in table:
first_name, last_name = row["Name"].split()
order = {
"item": row["Item"],
"zip": int(row["Zip"]),
"first_name": first_name,
"last_name": last_name
}
orders.append(order)
return orders
Here we are creating a new class called Orders
, that has one method called get_orders
, which accepts an argument excel
, containing the path to an Excel file. We are importing the Files
and Tables
classes from the RPA.Tables
and RPA.Excel.Files
modules, and using their methods in our Python code. This code resides in a file called Orders.py
in the libraries
subdirectory in our robot.
Adding the Orders
library to our .robot
code, we are then able to use the Get Orders
keyword in our own keyword like this:
*** Keywords ***
Collect orders
${orders}= Get orders ${EXCEL_FILE_PATH}
[Return] ${orders}
Summary
Libraries add new functionalities to your robot scripts. You can add existing libraries using available packages such as rpaframework
or create your own using Python code. You need to follow a set of simple conventions so that your Python methods are recognized as Robot Framework keywords. You can use rpaframework
either in Robot Framework or import its modules into your custom Python libraries.
Further reading
This article is only an introduction. There is more to learn about this topic on the Robot Framework User Guide.
There are many good tutorials and information readily available to get more familiar with Python. You can start from the Python For Beginners page on python.org, for example.