SoFunction
Updated on 2024-10-30

How Jmeter Calls Python Scripts Using BeanShell Sampler

1. Add [BeanShell Sampler] to the thread group as follows:

2. Put the following piece of code into the script area of the [BeanShell Sampler]:

Points of Attention:

  • (1) The path of the Python script in the command is changed to the path of your own script, and -t is followed by the parameters that need to be passed into the Python script, which can be passed into the variables of jmeter, or can be passed into more than one parameter.
  • (2) Define the name of the variable referenced in Jmeter, remember the name of the variable, which can be used later when jmeter is called.
import ;
import ;
 
// 1. Change the path in the command to the path of your own script, and -t followed by the parameters that need to be passed to the Python script, which can be passed to the jmeter variables.
String command = "cmd /c python E://python_project//Python-Auto//python_jmeter//zbg_password_rsa.py  -t ${pubKey}";
 
String var;
Runtime rt = ();
Process pr = (command);
 
();
 
BufferedReader b = new BufferedReader(new InputStreamReader(()));
String line = "";
StringBuilder response = new StringBuilder();
while ((line = ()) != null) {
    (line);
 
} 
String response_data = ();
 
(response_data);
();
 
var = ();
 
// 2. Define the names of the variables referenced in Jmeter. jmeter can call the variables directly from behind using ${variable name};
("password_str",var);
 
//print the var to the log, add the following code if necessary
//(var);

As shown in the figure below:

3, in Python, you need the following code to get jmeter incoming values, after Python processing, in the use of printing functions to jmeter (BeanShell sampler script in the role of the Java code is to accept the value passed by the Python script, and transformed into a variable that can be directly called by jmeter).

import argparse
# Get the value passed in by jmeter and assign it to the variable ticket, which can be called by Python.
parser = ()
parser.add_argument("-t", "--ticket", help="Here's the ticket.")
args = parser.parse_args()
ticket = 
#print('The value you entered: {}'.format(ticket))
 
# This is the Python script process code, omitted
 
# Finally Python passes the processed value to jmeter, that is, just print it directly
print('Fill in the values that need to be passed to jmeter here')

to this article on how to use Jmeter BeanShell sampler call Python script article is introduced to this , more related Jmeter call Python script content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future !