C++调用Python函数,获取Ping某网站的延迟时间与丢包率

1.Python函数的编写

# -*- coding: utf-8 -*-

import subprocess
import re
import sys

def get_ping_result(ip_address):
    
    #调用系统自带的ping.exe实现PING domain,返回值为:ip,丢包率,最短,最长,平均
    p = subprocess.Popen(["ping.exe", ip_address], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
    out = p.stdout.read()
    print out

    ## Pinging www.a.shifen.com [115.239.211.112] with 32 bytes of data
    ## Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)   数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
    ## Minimum = 37ms, Maximum = 38ms, Average = 37ms   最短 = 37ms,最长 = 77ms,平均 = 48ms

    regIP = r'\[\d+\.\d+\.\d+\.\d+\]'
    regLost = r'\(\d+%'
    regLatency = u'\= \d+ms'

    #regAverage = u'Average = \d+ms|平均 = \d+ms'
    #average = re.search(regAverage, out)
    #if average:
    #    average = filter(lambda x:x.isdigit(),average.group())
        
    ip = re.search(regIP, out)
    lost = re.search(regLost, out)
    
    latency = re.findall(regLatency, out)

    if ip:
        ip = ip.group()[1:-1]
    else:
        return "100","0","0","0"
    
    if lost:
        lost = lost.group()[1:]
        lostmum = filter(lambda x:x.isdigit(),lost)
        
    num = len(latency)
    
    if  num == 3:
        minimum = filter(lambda x:x.isdigit(),latency[0])
        maximum = filter(lambda x:x.isdigit(),latency[1])
        average = filter(lambda x:x.isdigit(),latency[2])
    
    '''for r in latency:
        minimum = filter(lambda x:x.isdigit(),r)
        print minimum'''
        
    return lostmum,minimum,maximum,average

'''if __name__ == '__main__':
    ping_result = get_ping_result('www.baidu.com')
    print(ping_result)'''


2.C++调用Python,并获取Python的返回值

#include <iostream>

#include <Python.h>
using namespace std;
int main( int argc, char * argv[] )
{
	// 初始化Python  
	//在使用Python系统前,必须使用Py_Initialize对其  
	//进行初始化。它会载入Python的内建模块并添加系统路  
	//径到模块搜索路径中。这个函数没有返回值,检查系统  
	//是否初始化成功需要使用Py_IsInitialized。  
	Py_Initialize();  

	// 检查初始化是否成功  
	if ( !Py_IsInitialized() ) {  
		return -1;  
	}

	// 添加当前路径  
	//把输入的字符串作为Python代码直接运行,返回0  
	//表示成功,-1表示有错。大多时候错误都是因为字符串  
	//中有语法错误。  
	PyRun_SimpleString("import sys");  
	PyRun_SimpleString("print '---import sys---'");   
	PyRun_SimpleString("sys.path.append('./')");  
	PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;

	// 载入名为python_getping的脚本  
	pName = PyString_FromString("python_getping");  
	pModule = PyImport_Import(pName);  
	if ( !pModule ) {  
		printf("can't find python_getping.py");  
		getchar();  
		return -1;  
	}  
	pDict = PyModule_GetDict(pModule);  
	if ( !pDict ) {  
		return -1;  
	}  

	// 找出函数名为get_ping_result的函数  
	printf("----------------------\n");  
	pFunc = PyDict_GetItemString(pDict, "get_ping_result");  
	if ( !pFunc || !PyCallable_Check(pFunc) ) {  
		printf("can't find function [get_ping_result]");  
		getchar();  
		return -1;  
	}  

	// 参数进栈  
	*pArgs;  
	pArgs = PyTuple_New(1);

	//  PyObject* Py_BuildValue(char *format, ...)  
	//  把C++的变量转换成一个Python对象。当需要从  
	//  C++传递变量到Python时,就会使用这个函数。此函数  
	//  有点类似C的printf,但格式不同。常用的格式有  
	//  s 表示字符串,  
	//  i 表示整型变量,  
	//  f 表示浮点数,  
	//  O 表示一个Python对象。  
	pArgs= Py_BuildValue("(s)","www.baidu.com");
	PyObject * result = PyEval_CallObject(pFunc,pArgs);

	//Python返回一个值时,使用PyString_AsString解析;
	/*char * resultStr = PyString_AsString(result);
	std::cout << resultStr << std::endl;*/

	char* lostmum;
	char* minimum;
	char* maximum;
	char* average;

	//Python返回多个值时,使用PyArg_ParseTuple解析;
	PyArg_ParseTuple(result,"s|s|s|s",&lostmum,&minimum,&maximum,&average);//分析返回的元组值  
	if(result)  
	{  
		printf("丢包率:%s%%\n",lostmum);  
		printf("最短:%sms\n",minimum);  
		printf("最长:%sms\n",maximum);  
		printf("平均:%sms\n",average);  
	} 
	//PyTuple_SetItem(pArgs, 0, Py_BuildValue("s","www.baidu.com"));

	 调用Python函数  
	//PyObject * result = PyObject_CallObject(pFunc, pArgs);
	//char * resultStr;
	//int cval = PyArg_Parse(result, resultStr);

	//std::cout << resultStr << std::endl;
	Py_DECREF(pName);  
	Py_DECREF(pArgs);  
	Py_DECREF(pModule);  

	// 关闭Python  
	Py_Finalize();
	system( "pause" );
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值