Commit 5907af94 authored by wanli's avatar wanli

Initial commit

parents
Pipeline #584 canceled with stages
__pycache__
*.pro.*
\ No newline at end of file
# 常用API
## 1、运行Python指令
```python
PyRun_SimpleString("print(os.getcwd(),a)");
pyext.eval(R"(a+='qwer')");
```
## 2、加载Python模块
```python
PyObject * pModule =PyImport_ImportModule("tp"); # test:Python文件名,若脚本有错则返回空
PyRun_SimpleString("import os");
```
## 3、给Python的变量赋值
对于数值,使用Py_BuildValue:
```python
Py_BuildValue("") # None
Py_BuildValue("i", 123) # 123
Py_BuildValue("iii", 123, 456, 789)# (123, 456, 789)
Py_BuildValue("s", "hello") # 'hello'
Py_BuildValue("ss", "hello", "world") # ('hello', 'world')
Py_BuildValue("s#", "hello", 4) # 'hell'
Py_BuildValue("()") # ()
Py_BuildValue("(i)", 123) # (123,)
Py_BuildValue("(ii)", 123, 456) # (123, 456)
Py_BuildValue("(i,i)", 123, 456) # (123, 456)
Py_BuildValue("[i,i]", 123, 456) # [123, 456]
Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) # {'abc': 123, 'def': 456}
```
对于其他数据结构,使用相应的函数设置,例如:
```python
PyObject *pArgs = PyTuple_New(1);
PyObject *pDict = PyDict_New(); # 创建字典类型变量
PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "YQC")); # 往字典类型变量中填充数据
PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); # 往字典类型变量中填充数据
PyTuple_SetItem(pArgs, 0, pDict);# 0---序号 将字典类型变量添加到参数元组中
```
构造好对象以后,通过PyObject_SetAttrString来设置进入Python中:
```python
PyObject *ps=PyUnicode_DecodeUTF8(val,strlen(val),"ignore"); # 构造了一个对象
PyObject_SetAttrString(p_main_Module,key,ps); # 设置
```
## 4、获取Python变量的值
首先取得变量的指针,然后通过PyArg_Parse解析
```python
pModule =PyImport_ImportModule("__main__");
pReturn = PyObject_GetAttrString(pModule, "a"); # 可以获得全局变量
int size = PyDict_Size(pReturn);
PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age");
int newAge;
PyArg_Parse(pNewAge, "i", &newAge);
```
对于元组的解析:
```python
int ok;
ok = PyArg_ParseTuple(args, "s", &s); # Python call: f('whoops!')
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); # Python call: f(1, 2,'three')
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); # Python call: f((1, 2), 'three')
ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);# Python calls:
# f('spam')
# f('spam', 'w')
# f('spam', 'wb', 100000)
```
## 5、调用Python函数
```python
PyObject * pfun=PyObject_GetAttrString(pModule, "testdict"); # testdict:Python文件中的函数名
PyObject *pReturn = PyEval_CallObject(pfun, pArgs); # 调用函数
```
## 6、设置函数让Python调用
首先定义c函数,然后声明方法列表,然后声明模块,然后增加这个模块,最后调用
```python
static int numargs = 1890;
static PyObject* emb_numargs(PyObject *self, PyObject *args) # C函数
{
if(!PyArg_ParseTuple(args, ":numargs"))
return NULL;
return PyLong_FromLong(numargs);
}
static PyMethodDef EmbMethods[] = { # 方法列表
{
"numargs",
emb_numargs,
METH_VARARGS,
"Return the number of arguments received by the process."
},
{
NULL, NULL, 0, NULL
}
};
static PyModuleDef EmbModule = { # 模块声明
PyModuleDef_HEAD_INIT,
"emb",
NULL,
-1,
EmbMethods,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void) # 模块初始化函数
{
return PyModule_Create(&EmbModule);
}
# 增加模块:
PyImport_AppendInittab("emb", &PyInit_emb); # 增加一个模块
```
\ No newline at end of file
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
INCLUDEPATH += "D:\Program Files\Python\include"
LIBS += -L"D:\Program Files\Python" -lpython38
SOURCES += \
main.c \
test_CallFunction.c \
test_CallModuleClass.c \
test_CallModuleClassReturnTuple.c \
test_CallModuleFunction.c \
test_CallModuleFunctionByParameters.c \
test_CallPythonFunction.c \
test_CallPythonSentiment.c \
test_CallScript.c \
test_RunSimpleString.c
DISTFILES += \
graph.py \
sample.py \
demo.py \
multiply.py \
sentiment.py
HEADERS += \
test_case.h
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
def print_arg(str):
print(str)
def add(a, b):
print('a = ', a)
print('b = ', b)
return a + b
class Class_A:
def __init__(self):
print("init")
def func(self, str):
print('hello', str)
return str
class dedecms_get_webshell:
def __init__(self):
self._run = True
# must rewrite function
def check(self, site, port):
print("Exploiting Host:%s, Port:(%d)......" % (site, port))
flag = 1
if flag:
content = {"flag": 1,
"content": "POST http://www.baidu.com/shell.php (cmd)"}
else:
content = {"flag": 0,
"content": "POST http://www.baidu.com/shell.php (cmd)"}
return content
if __name__ == "__main__":
site = "www.baidu.com"
port = 80
obj = dedecms_get_webshell()
ret = obj.check(site, port)
print(ret)
# -*- coding:utf-8 -*-
import xlsxwriter
def create_graph(a, b, c, d, e, f):
# 创建一个excel
workbook = xlsxwriter.Workbook("排序算法比较结果.xlsx")
# 创建一个sheet
worksheet = workbook.add_worksheet()
# worksheet = workbook.add_worksheet("bug_analysis")
# 自定义样式,加粗
bold = workbook.add_format({'bold': 1})
# --------1、准备数据并写入excel---------------
# 向excel中写入数据,建立图标时要用到
headings = ["排序方法", "排序时间"]
data = [["简单选择排序", "直接插入排序", "冒泡排序", "快速排序",
"两路合并排序", "堆排序"], [a, b, c, d, e, f]]
# 写入表头
worksheet.write_row('A1', headings, bold)
# 写入数据
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
# --------2、生成图表并插入到excel---------------
# 创建一个柱状图(column chart)
chart_col = workbook.add_chart({'type': 'column'})
# 配置第一个系列数据
chart_col.add_series({'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$B$2:$B$7', 'line': {'color': 'red'}, })
# 这里的sheet1是默认的值,因为我们在新建sheet时没有指定sheet名
# 如果我们新建sheet时设置了sheet名,这里就要设置成相应的值
# 设置图表的title 和 x,y轴信息
chart_col.set_title({'name': "排序算法结果"})
chart_col.set_x_axis({'name': "排序方法"})
chart_col.set_y_axis({'name': "花费时间(ms)"})
# 设置图表的风格
chart_col.set_style(1)
# 把图表插入到worksheet以及偏移
worksheet.insert_chart('A10', chart_col, {'x_offset': 25, 'y_offset': 10})
workbook.close()
return 0
if __name__ == "__main__":
create_graph(10, 40, 50, 20, 10, 50)
#include <stdio.h>
#include "test_case.h"
void getCurrentEnv()
{
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
return;
}
int main(int argc, const char* argv[])
{
printf("argc => %d \r\n", argc);
printf("argv => %s \r\n", *argv);
test_SimpleString(); // 执行一行python脚本语句
test_CallFunction(); // repl 一条语句一条语句地执行
test_CallPythonFunction(); // 测试调用python脚本里面的函数
test_CallModuleFunction(); // 调用模块中的一个普通函数
test_CallModuleFunctionByParameters(); // 调用模块中的一个函数(多參数,带返回值)
test_CallModuleClass(); // 调用模块中简单的一个类(单个返回值)
test_CallModuleClassReturnTuple(); // 调用模块中一个简单的类(返回值是个元组)
test_CallScript(); // 调用一个python脚本
system("PAUSE");
return 0;
}
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
# __name__ = "multiply"
def multiply(a, b):
print("Will compute", a, "times", b)
c = 0
for i in range(0, a):
c += b
return c
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
def hello():
print(" Sample.py hello!")
def add(a, b):
return a + b
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
#import sentimentweb.info as s
#from s import MyDict
#import sentimentweb.info.MyDict as d
#from sentimentweb.info import MyDict, feature_selection_trials, classify2
from sentimentweb.info import feature_selection_trials, MyDict, classify2
#text = 'Good afternoon. My name is Russel, and I\'m a senior wilderness explorer. Are you in need of any assistance today, Sir?'
#text2 = 'I hate this person with a passion, so I couldn\'t enjoy the movie'
def analyze(text):
#from sentimentweb.info import feature_selection_trials
#from sentimentweb.info import MyDict
#t = MyDict()
#print(t)
feature_selection_trials()
#print(classify2(text))
#print(classify2(text2))
#print(classify2(text3))
#value = classify2(text3)
#return {
# 'sentiment': 'positive' if value[0] else 'negative',
# 'certainty': value[1]
#}
return classify2(text)
#def main():
# analyze("Hi there, my name is a name of happy happy happy.")
#
#main()
#include "test_case.h"
void test_CallFunction() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
PyRun_SimpleString("x = 10");
PyRun_SimpleString("y = 20");
PyObject* mainModule = PyImport_ImportModule("__main__");
PyObject* dict = PyModule_GetDict(mainModule);
PyObject* resultObject = PyRun_String("x + y", Py_eval_input, dict, dict);
if(resultObject)
{
long result = PyLong_AsLong(resultObject);
printf("x + y =====> %ld\r\n", result);
Py_DECREF(resultObject);
}
// Destroy the Python interpreter.
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
void test_CallModuleClass() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
getCurrentEnv();
PyObject *pModule = NULL, *pDict = NULL, *pClass = NULL, *pInstance = NULL, *result = NULL;
pModule = PyImport_ImportModule("demo"); // 引入模块
pDict = PyModule_GetDict(pModule); // 获取模块字典属性
pClass = PyDict_GetItemString(pDict, "Class_A"); // 通过字典属性获取模块中的类
pInstance = PyObject_CallObject(pClass, NULL); // 实例化获取的类
result = PyObject_CallMethod(pInstance, "func", "(s)", "python_000"); // 调用类的方法
char* name = NULL;
PyArg_Parse(result, "s", &name); // 将python类型的返回值转换为c/c++类型
printf("%s\n", name);
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
void test_CallModuleClassReturnTuple() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
getCurrentEnv();
PyObject *pModule = NULL, *pDict = NULL,*pClass = NULL, *pInstance = NULL, *result = NULL;
pModule =PyImport_ImportModule("demo"); // 引入模块
pDict = PyModule_GetDict(pModule); // 获取模块字典属性
pClass = PyDict_GetItemString(pDict, "dedecms_get_webshell"); // 通过字典属性获取模块中的类
pInstance = PyObject_CallObject(pClass, NULL);
result = PyObject_CallMethod(pInstance, "check", "(s,i)", "www.so.com", 80);
int flag;
char* content = NULL;
PyObject *obj_content =PyDict_GetItemString(result, "content");
PyArg_Parse(obj_content, "s", &content); // python字符串转换为c字符串
PyObject *obj_flag =PyDict_GetItemString(result, "flag");
PyArg_Parse(obj_flag, "i", &flag); // python整形转换为c整形
printf("content: %s, flag: %d\n", content, flag);
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
void test_CallModuleFunction() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
getCurrentEnv();
PyObject *pModule = NULL, *pFunc = NULL, *pArg = NULL;
pModule = PyImport_ImportModule("demo"); // 引入模块
pFunc = PyObject_GetAttrString(pModule, "print_arg");// 直接获取模块中的函数
pArg = Py_BuildValue("(s)", "hello_python"); // 參数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型。元组中的python类型查看python文档
PyEval_CallObject(pFunc, pArg); // 调用直接获得的函数。并传递參数
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
return;
}
#include "test_case.h"
void test_CallModuleFunctionByParameters() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
getCurrentEnv();
PyObject *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pArg = NULL, *result = NULL;
pModule = PyImport_ImportModule("demo"); // 引入模块
pDict = PyModule_GetDict(pModule); // 获取模块字典属性 //相当于Python模块对象的__dict__ 属性,得到模块名称空间下的字典对象
pFunc = PyDict_GetItemString(pDict, "add"); // 从字典属性中获取函数
pArg = Py_BuildValue("(i, i)", 1, 2); // 參数类型转换,传递两个整型參数
result = PyEval_CallObject(pFunc, pArg); // 调用函数。并得到python类型的返回值
int sum;
PyArg_Parse(result, "i", &sum); // 将python类型的返回值转换为c/c++类型
printf("sum = %d\n", sum);
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
void test_CallPythonFunction(void) {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
// Initialize the Python interpreter.
// Py_SetPythonHome(L"D:/Anaconda3");
Py_Initialize();
getCurrentEnv();
// Create some Python objects that will later be assigned values.
PyObject *pModule, *pDict, *pFunc_add, *pFunc_hello, *pArgs, *pValue, *pValue2;
// Import the file as a Python module.
pModule = PyImport_ImportModule("sample");
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
pFunc_add = PyDict_GetItemString(pDict, "add");
pFunc_hello = PyDict_GetItemString(pDict, "hello");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// Convert 2 to a Python integer.
pValue = PyLong_FromLong(6);
pValue2 = PyLong_FromLong(8);
// Set the Python int as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue2);
// Call the function with the arguments.
PyObject_CallObject(pFunc_hello, NULL);
PyObject* pResult = PyObject_CallObject(pFunc_add, pArgs);
// Print a message if calling the method failed.
if (pResult == NULL)
printf("Calling the add method failed.\n");
// Convert the result to a long from a Python object.
long result = PyLong_AsLong(pResult);
// Print the result.
printf("Calling Python to find the sum of 6 and 8.\n");
printf("The result is %ld.\n", result);
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
float getSentiment(char *sentence)
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
// Py_Initialize();
// Refer to local file, not python module
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyRun_SimpleString("from sentimentweb.info import feature_selection_trials, MyDict, classify2");
pName = Py_BuildValue("(s)", "sentiment");
// error checking should occur
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL)
{
pFunc = PyObject_GetAttrString(pModule, "analyze");
// pFunc is a new reference
if (pFunc && PyCallable_Check(pFunc))
{
pArgs = PyTuple_New(1);
pValue = Py_BuildValue("(s)", sentence);
if (!pValue)
{
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
// pValue reference stolen here:
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL)
{
int positive = PyTuple_GetItem(pValue, 0) == Py_True;
double probability = PyFloat_AsDouble(PyTuple_GetItem(pValue, 1));
//printf("Result of call: %o\n", PyTuple_AsTuple(pValue));
printf("Sentiment is: %s. Probability is: %0.3f.\n",
(positive) ? "positive" : "negative", probability);
double d = ((positive) ? 1 : -1) * probability;
if (d > 1)
d = 1;
if (d < -1)
d = -1;
Py_DECREF(pValue);
return d;
}
else
{
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
return 1;
}
}
else
{
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function analyze.\n");
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else
{
PyErr_Print();
fprintf(stderr, "Failed to comprehend \"%s\", I guess.\n", sentence);
return 1;
}
// Py_Finalize();
return 0;
}
#include "test_case.h"
void test_CallScript() {
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
// 待传参数
int time[6] = {1,2,3,4,5,6};
// 初始化python
Py_Initialize();
// 检查初始化是否成功
if (!Py_IsInitialized())
{
printf("初始化失败\n");
Py_Finalize();
}
// 设置python模块,搜寻位置,文件放在.c文件一起
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
// 获取python文件名,导入模块(我这里的py文件是graph.py)
pModule = PyImport_ImportModule("graph");
if (!pModule) {
printf("py文件导入失败\n");
Py_Finalize();
} else {
//直接获取模块中的函数
pFunc = PyObject_GetAttrString(pModule, "create_graph");
//验证函数是否获取成功
if (!pFunc) {
printf("函数导入失败\n");
Py_Finalize();
}
//将c/c++类型数据转换为python类型,利用元组传递
pArgs = PyTuple_New(6);
pValue = PyLong_FromLong(time[0]);
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyLong_FromLong(time[1]);
PyTuple_SetItem(pArgs, 1, pValue);
pValue = PyLong_FromLong(time[2]);
PyTuple_SetItem(pArgs, 2, pValue);
pValue = PyLong_FromLong(time[3]);
PyTuple_SetItem(pArgs, 3, pValue);
pValue = PyLong_FromLong(time[4]);
PyTuple_SetItem(pArgs, 4, pValue);
pValue = PyLong_FromLong(time[5]);
PyTuple_SetItem(pArgs, 5, pValue);
//调用直接获得的函数,并传递参数
pValue = PyObject_CallObject(pFunc, pArgs);
//释放python
Py_Finalize();
printf("success");
}
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
}
#include "test_case.h"
void test_SimpleString()
{
printf("=======> test funtion %s come in <========\r\n", __FUNCTION__);
Py_Initialize();
PyRun_SimpleString("print('hello python')");
Py_Finalize();
printf("=======> test funtion %s leave out <========\r\n\r\n\r\n", __FUNCTION__);
return;
}
#ifndef TEST_CASE_H
#define TEST_CASE_H
#include <Python.h>
void test_SimpleString(void);
void test_CallPythonFunction(void);
void test_CallFunction(void);
void test_CallModuleFunction(void);
void test_CallModuleFunctionByParameters(void);
void test_CallModuleClass(void);
void test_CallScript(void);
void test_CallModuleClassReturnTuple(void);
float getSentiment(char* sentence);
void getCurrentEnv();
#endif // TEST_CASE_H
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment