在 Web 服务中异步调用 Python 脚本

释放双眼,带上耳机,听听看~!

CGI 中需要调用一个 Python 脚本,脚本去更新执行 update 的 sql 语句,时间较长,超过了 Web 服务器的最大连接时间,因此需要使用异步调用脚本的方式。

同步方式


1
2
3
4
5
6
1char command[300] = "~/tools/read_emoji_text.py";
2iRet = system(command);
3MMJsonOutput *pOutResult = new MMJsonOutput;
4pOutResult->GetResult()["errcode"] = iRet;
5pOutResult->GetResult()["msg"] = "upload file success";`
6

很明显,Python 脚本执行完后才给请求返回数据

异步方式


1
2
3
4
5
6
7
8
9
10
11
12
13
1if (0 == fork()) {
2    char command[300] = "~/tools/read_emoji_text.py";
3    iRet = system(command);
4    _exit(127);
5}
6else {
7    MMJsonOutput *pOutResult = new MMJsonOutput;
8    pOutResult->GetResult()["errcode"] = iRet;
9    pOutResult->GetResult()["msg"] = "upload file success";
10
11    return pOutResult;
12}
13

主进程直接返回数据,在子进程中去调用同步的 system 函数,执行 Python 脚本。这里还可以使用更底层的 execl 系统调用来执行脚本。

遇到的问题

使用异步的方式,iRet 的返回值一直为 256,相当于 read_emoji_text.py 执行返回值为 256 >> 8 = 1。出现这个错误的原因是打开文件的路径写的是相对路径,而二进制在执行时并不是在这个路径。


1
2
3
4
1def get_mark_data():
2    file = open("~/tools/emoji_data")
3    revise_list = []
4

参考

linux system函数的学习

System Return Code was 256

给TA打赏
共{{data.count}}人
人已打赏
安全技术

spring cache

2022-1-11 12:36:11

安全运维

Linux(内核剖析):01---Unix历史、Linux简介

2021-8-18 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索