C 內嵌Python架構實現

2022-02-21 00:53:11 字數 2557 閱讀 6284

c#通過ironpython內嵌python指令碼,實現了對業務邏輯抽象及判斷,適合在大量訂單需要進行校驗的場合使用。

比如,貸款時會對使用者進行核查,核查過程可能存在多個節點,並且節點可能會隨著政策而不斷改變,每個節點就相當於乙個指令碼,通過指令碼的出口關鍵字來確定流程分支走向。

大概業務流程圖如下:

**實現部分

1、c#**

using ironpython.hosting;

using microsoft.scripting;

using microsoft.scripting.hosting;

using system;

using system.collections.generic;

using system.io;

using system.linq;

using system.text;

using system.threading;

using system.threading.tasks;

namespace ironpython呼叫示例

filestream filestream = new filestream(logpath, filemode.openorcreate);

"------------------------以下是c#執行日誌資訊------------------------");

tryif (!file.exists(sourcecodepath))

string pythoncodecontent = file.readalltext(pythoncodepath).split(new string , stringsplitoptions.none);

string sourcecodecontent = file.readalltext(sourcecodepath).split(new string , stringsplitoptions.none);

if (sourcecodecontent == null || sourcecodecontent.length == 0)

liststrlist = new list(pythoncodecontent);

foreach (var item in sourcecodecontent)

string codes = "";

foreach (var s in strlist)

scriptengine engine = python.createengine();

scriptsource source = engine.createscriptsourcefromstring(codes);

scriptscope scope = engine.createscope();

source.execute(scope);

dynamic performer = scope.getvariable("performer");

dynamic per = performer("1005");

per.run();

var out_param = per.out_param;

console.writeline(per.out_param);

console.readkey();

}catch (exception ex)

finally}}

}

2、python**,模板(pythoncode.txt)

#.coding=utf-8

import db_manager

class performer():

def __init__(self,in_param):

self.out_param = ''

self.in_param = in_param

def run(self):

3、節點指令碼(performer.py)

import datetime

def get_now_time():

self.out_param = str(datetime.datetime.now())

def get_user_count():

order_id = self.in_param

sql = "select * from user_info where id = "+ order_id +""

querys = db_manager.sqlserver().execute_query(sql)

if(len(querys) >= 5):

self.out_param = '業務辦理失敗,此使用者在全國範圍內辦理號碼已經超過了5個!'

else:

self.out_param = '初審通過,已進入人工審核階段!'

get_now_time()

get_user_count()

注意,此專案需要安裝ironpython,並且把裡面bin目錄複製到我們c# debug目錄下,專案源**:

python 內嵌C函式

yum install python devel.x86 64 include usr include python2.7 python.h int add int a,int b pyobject wrap add pyobject self,pyobject args static pymeth...

linux c內嵌執行python

編寫 test1.c include int main int argc,char argv 編譯 gcc g test1.c root python lib libpython2.7.a i root python include python2.7 l root python lib pytho...

VC內嵌Python指令碼

前言 tcl 在國內似乎很少有人用,據說因為用的人少,所以中文方面的資料非常少的 python 好像比較好學的,而且使用者群比tcl perl 要多,中文資料也蠻多的了,我也在學python 1.安裝python2.6.1到c python26 2.用vc2008 vc6.0不行 新建乙個vc專案,...