MAC 中 Jmeter 向 Python 脚本传参
大约 2 分钟零散知识Jmeter
1. 确定 python 版本
# python2 版本
python --version
# python3 版本
python3 --version

2. 创建 python 脚本
提示
Python 中 sys.argv 的用法解释:sys.argv 可以让 python 脚本从程序外部获取参数
- sys.argv 是一个列表,可用
[]
提取其中的元素,- 其第一个元素是程序本身,随后才依次是外部给予的参数,可以接受多个参数,每个参数用空格隔开即可。
- 获取外部传入的元素从 变量名[1] 开始获取
提示
脚本中 print()
的内容都可被 jmeter 接收,可以在 jmeter 中使用正则表达式提取器对相关参数进行提取。
# test.py
# sys 用于获取外部传入的参数
import sys
import hashlib
def loginMd5(username, password):
res = getMd5(username+password)
# print 用于将处理后的参数传给 jmeter
print({"md5": res})
def getMd5(value):
md5 = hashlib.md5()
md5.update(value.encode("utf-8"))
return md5.hexdigest()
loginMd5(sys.argv[1], sys.argv[2])
3. 创建脚本文件
提示
$1 $2 : 表示将 2 个参数传递给 python 文件 ( 或者使用 $1 $1 也是表示传两个参数 ) 。
# shell.sh
python3 /Users/xxx/Documents/AutomatedTesting/jmeter/test.py $1 $2
注意
Mac 系统后缀名为
.sh
文件, windows 系统后缀名为.bat
文件Mac 传输的 python 脚本的占位符为
$
,windows 占位符为%
4. jmeter 获取传参给 python 脚本
1. 获取 csv 文件数据

2. 使用 OS 进程提取器 向 python 脚本传参

5. 使用 正则表达式提取器 获取 python 打印的数据

6. 运行 jmeter 脚本即可查看加密后的数据

问题解答
1. 运行时提示没有文件权限

解决办法: 给 .sh
脚本赋予权限, 需要输入 电脑 密码
sudo chmod 777 /Users/xxx/Documents/AutomatedTesting/jmeter/shell.sh
