https://docs.python.org/3.7/c-api/intro.html#coding-standards
http://shouce.jb51.net/Python_jj/c_extensions/python_c_api.html
https://www.jianshu.com/p/c9f5f4ce3e7a?utm_campaign=maleskine
序列都可以进行的操作包括索引,切片,加,乘,检查成员 。最常见的是列表和元组
元组创建:只需要在括号中添加元素,并使用逗号隔开即可;元组的元素不能修改。
元组使用(),列表使用[]
#include <iostream>
#include <Python.h>
using namespace std;
std::string exec_shell(std::string ip,int port,std::string usr,std::string pwd,std::string strcmd);
std::string getMemRate();
#define MODULENAME "tools"
int main()
{
std::string ret;
ret = exec_shell("192.168.5.100",22,"root","123456",
"pwd");
cout<<"current path:\n"<<ret;
ret = exec_shell("192.168.5.100",22,"root","123456",
"cat /proc/version");
cout<<"sys verson:\n"<<ret;
ret = getMemRate();
cout<<"Mem rate:"<<ret;
cout<<"\n";
system("pause");
return 0;
}
std::string exec_shell(std::string ip,int port,std::string usr,std::string pwd,std::string strcmd)
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule(MODULENAME); //Python文件名
if (!pModule) {cout << ">>>>>pModule "<<endl; return "";}
pFunc= PyObject_GetAttrString(pModule, "exec_shell"); //Add:Python文件中的函数名
if (!pFunc) {cout << ">>>>>pFunc "<<endl; return "";}
//[1]输入参数:
PyObject *pArgs = PyTuple_New(2);
PyObject *pDict = PyDict_New(); //创建字典类型变量
PyDict_SetItemString(pDict, "ip", Py_BuildValue("s", ip.data())); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "port", Py_BuildValue("i", port)); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "username", Py_BuildValue("s", usr.data())); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "password", Py_BuildValue("s", pwd.data())); //往字典类型变量中填充数据
PyTuple_SetItem(pArgs, 0, pDict);//将字典类型变量添加到参数元组中
PyTuple_SetItem(pArgs, 1, Py_BuildValue("s", strcmd.data())); //将变量添加到参数元组中
//[2]调用
PyObject* pReturn = PyObject_CallObject(pFunc, pArgs);
//[3]返回值
char* ret;
PyArg_Parse(pReturn, "s", &ret);
Py_Finalize();
return std::string(ret);
}
std::string getMemRate(){
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule(MODULENAME); //Test001:Python文件名
if (!pModule) {cout << ">>>>>pModule "<<endl; return "";}
pFunc= PyObject_GetAttrString(pModule, "getMemRate"); //Add:Python文件中的函数名
if (!pFunc) {cout << ">>>>>pFunc "<<endl; return "";}
//[1]输入参数:
PyObject *pArgs = PyTuple_New(1);
PyObject *pDict = PyDict_New(); //创建字典类型变量
PyDict_SetItemString(pDict, "ip", Py_BuildValue("s", "172.16.5.171")); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "port", Py_BuildValue("i", 22)); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "username", Py_BuildValue("s", "root")); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "password", Py_BuildValue("s", "hhkj")); //往字典类型变量中填充数据
PyTuple_SetItem(pArgs, 0, pDict);//0---序号 将字典类型变量添加到参数元组中
//[2]调用
PyObject* pReturn = PyObject_CallObject(pFunc, pArgs);
//[3]返回值
char* ret;
PyArg_Parse(pReturn, "s", &ret);
Py_Finalize();
return std::string(ret);
}