How to run python code in robot framework I have my python code in dict.py file and I want to call this file in robot framework and get output there
Hi Ashwini,
In robot framework you don’t normally call a python file, but rather python functions within those python files.
There are several ways to do this and without knowing the content of dict.py or what you are trying to achieve it’s hard to know which approach to recommend for you.
- What do you hope to achieve by running dict.py?
- What do you hope to get back from dict.py?
Here are examples of some of the ways you could use python in Robot Framework:
- call a python function and get it’s result as a variable → Evaluate
- create some dynamic runtime variables → Taking variable files into use
- use a python function as a Robot Framework keyword → Creating test library class or module
- execute a python script as a seperate process → Run Process
There are other options as well these are just the most common,
Dave.
(post deleted by author)
In that case Run Process is what you probably want, something like this should give you a good starting point:
${result}= Run Process python3 dict.py
Log ${result}
Log ${result.stdout}
Depending on your machine, you might need python, python.exe python3.exe, you might need the path to python as well (if it’s not in your path) and you might need the path to the python file, it all depends on how your machine is setup.
Dave.
(post deleted by author)
Check the log.html file for the Log ${result.stdout}
it will contain the output from dict.py
you can use Log To Console to output to the console.
Dave.
(post deleted by author)
(post deleted by author)
(post deleted by author)
FYI when putting code in the forum post use a code block:
```
< your code here >
```
Lets start with the basics:
Your formatting got messed up for dict.py, I had a go at fixing it and got this, is it right?
class demof:
def int(self, input_dict):
output_dict={}
for key, value in input_dict.items():
numeric_value=''.join(filter(str.isdigit,value))
if numeric_value:
numeric_value= int(numeric_value)
if '(' in key and ')' in key:
index=int(key[key.find('(')+ 1:key.find(')')])
key = key [:key.find(')')]
else:
index=0
if key not in output_dict:
output_dict[key]={}
output_dict[key][index]= numeric_value
print(output_dict)
input_dict= {'Maintenance contract(0)': '109 630 €', 'Recommended repairs(0)': '0 €', 'Estimated(17)': '15 695 €', 'Upgrade(0)': '0 €'}
d1=demof(input_dict)
I tried to run that and got
% python3 dict.py
Traceback (most recent call last):
File "/tmp/Ashwini/dict.py", line 21, in <module>
d1=demof(input_dict)
TypeError: demof() takes no arguments
So I tried to modify it and changed
def int(self, input_dict):
to
def __init__(self, input_dict):
Then when I ran it, I got no output. adding in some extra print statements I noticed all the keys have (
and )
in them, so they never get to the print(output_dict)
line, so of corse there’s no output.
So as a demonstration for you I created the following files:
demo_dict.py
class demof:
def __init__(self, input_dict):
output_dict={}
for key, value in input_dict.items():
print("key:", key, " value:", value)
input_dict= {'Maintenance contract(0)': '109 630 €', 'Recommended repairs(0)': '0 €', 'Estimated(17)': '15 695 €', 'Upgrade(0)': '0 €'}
d1=demof(input_dict)
Running this gives:
% python3 demo_dict.py
key: Maintenance contract(0) value: 109 630 €
key: Recommended repairs(0) value: 0 €
key: Estimated(17) value: 15 695 €
key: Upgrade(0) value: 0 €
Ashwini.robot
*** Settings ***
Library Process
*** Test Cases ***
Ashwini
${result}= Run Process python3 demo_dict.py
Log ${result}
Log ${result.stdout}
Log To Console ${result}
Log To Console ${result.stdout}
Running this gives:
% robot Ashwini.robot
==============================================================================
Ashwini
==============================================================================
Ashwini ...<result object with rc 0>
.key: Maintenance contract(0) value: 109 630 €
key: Recommended repairs(0) value: 0 €
key: Estimated(17) value: 15 695 €
key: Upgrade(0) value: 0 €
Ashwini | PASS |
------------------------------------------------------------------------------
Ashwini | PASS |
1 test, 1 passed, 0 failed
==============================================================================
Output: /tmp/Ashwini/output.xml
Log: /tmp/Ashwini/log.html
Report: /tmp/Ashwini/report.html
If you can replicate what I did, then from there hopefully you should be able to work out why you got no output.
Dave.
(post deleted by author)
Not sure I understand?
- You fetched these values with python, robot framework, something else?
- How do they get put into dict.py?
- Is the whole purpose of dict.py to update this dictionary of values?
Just trying to understand the whole picture.
Dave.
(post deleted by author)
(post deleted by author)
Hi Ashwini,
Always fun to have a challange
Ashwini_dict.robot
*** Settings ***
Library String
Library Collections
*** Variables ***
*** Test Cases ***
Ashwini Convert Dict
&{input_dict}= Get Dict From App
Log ${input_dict}
&{output_dict}= Convert App Dict ${input_dict}
Log ${output_dict}
*** Keywords ***
Get Dict From App
${input_dict}= Evaluate json.loads('{"Maintenance contract(0)": "109 630 €", "Recommended repairs(0)": "0 €", "Estimated(17)": "15 695 €", "Upgrade(0)": "0 €"}') modules=json
[Return] ${input_dict}
Convert App Dict
[Arguments] ${input_dict}
&{output_dict}= Create Dictionary
FOR ${key} ${val} IN &{input_dict}
Log "${key} | ${val}"
# break apart the key
${keyx} = Replace String ${key} ) ${EMPTY}
# @{keyparts}= Get Regexp Matches "${key}" ([^\\(]*)\\(([^\\)]*)
@{keyparts}= Split String ${keyx} (
Log ${keyparts}
# make the value to a number
# first remove the €
${noero} = Replace String ${val} € ${EMPTY}
${num}= Convert To Integer ${noero}
&{val_dict}= Create Dictionary
Set To Dictionary ${val_dict} ${keyparts[1]} ${num}
Log ${val_dict}
Set To Dictionary ${output_dict} ${keyparts[0]} ${val_dict}
END
[Return] ${output_dict}
Dave.
Thank yo so much Dave I got the required solution
Hi Dave,
Thanks for the solution I Tried to get that output from last two days but failed to do that and you solved that in couple of hours “Great”. I have some doubt:
- did you hardcoded any data here.
2.Can we use this code in real time(can be used in project framework) also ??
3.If I have thousands of data coming from UI and I want to convert all those data into same format then how can I do that can you please tell me the code for that ?
4.How to call python file or function in robot framework(what are the required things for that) If possible can you explain by calling python file/function in robot framework
Can you explain the code little bit it will be great!!!
TIA
Hi Ashwini,
The data returned by Get Dict From App
is hard coded to simulate you getting the output from UI.
Everything in Convert App Dict
is dynamic, but based on the example data you gave, if you get data without the keys having brackets ( ) or values that have different currency symbols other than €, i.e. $ or ₹ then Convert App Dict
won’t handle those situations as is so you might need to modify it if you need to handle those conditions.
Yes, you should be able to just drop the keyword Convert App Dict
into your test file or resource file and use it in your test case the same way I called it in my example test case Ashwini Convert Dict
Thousands of data coming from UI in the same dictionary? if so just pass the dictionary to Convert App Dict
it will keep going regardless how many items in the dictionary, it will just take longer than the 22 ms the small dictionary took
The documentation I linked to in my first post here had examples for each type, if you get stuck following the examples in the documentation, quote the bit you don’t understand and I’ll try to explain it for you.
-
Convert App Dict
takes the original dictionary as an input - First I created a new output dictionary
-
FOR ${key} ${val} IN &{input_dict}
this should be pretty self explanatory, we are iterating over the dictionary one key/value pair at a time - inside the for I left comments for explaining what I was doing:
# break apart the key
# make the value to a number
# first remove the €
- after that I converted the value with the € removed to an interger (whole number)
- then I created a new value dictionary with the part of the key that was in brackets as the key and the interger value as the value
- then I put the new value dictionary into the output dictionary with the first part of the original key (before the brackets) as the key and the new value dictionary as the value
- then I move on to the next key value pair
- once all processed the output dictionary is returned from the
Convert App Dict
keyword.
You should be able to run the example and then work your way though log.html steps comparing the results with the code to see what’s going on.
Dave.
Hi Dave,
When I run my programs with robot command it shows error message as "robot : The term ‘robot’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again
currently I’m using python -m robot file_path but my lead said that please resolve the error and run files with robot commands only
can you please help me I tried many times by uninstalling pycharm but the error keeps coming
TIA
Currently I’m using windows OS and my robot.exe file is in location \venv\scripts location my python file is also in the same location(\venv\scripts) Can you please help me to resolve this error and please provide steps to add robot file in path