Calling Python in C #

Source: Internet
Author: User

My computer environment is using. NET framework4.5.1, if it doesn't work during debugging please note

I'm using the visual Studion 2017,python component: http://ironpython.codeplex.com/releases/view/

The downloaded version is 2.7, and after the download installs, remember to introduce the following three DLLs under the installation path

(1) First of all, a simple function, in C # code to execute the python string, the content is as follows:

(2) C # call Python file:

In the current directory, create a new suffix named py file, the file name is amoutdisc.py content as follows

Dicamt = 0.05RETAMT = amtif amt>25:   Retamt = amt-(Amt*dicamt)

The file defines a python file, then calls the Python file in C # code, gives the file a parameter, and, in particular, passes the parameters to the AMT, and finally gets the Retamt variable in the python file in the code.

Value, the following code is specified:

                Scriptruntime scriptruntime =python.createruntime ();                ScriptEngine Pytheng = Scriptruntime.getengine ("Python");                Scriptsource Scriptsource = Pytheng.createscriptsourcefromfile ("amoutdisc.py");                Scriptscope scope = Pytheng.createscope ();                Scope. SetVariable ("Prodcount", Convert.ToInt32 ("34343"));                Scope. SetVariable ("Amt", Convert.todecimal ("434"));                Scriptsource.execute (scope);                Dynamic A = scope. GetVariable ("Retamt");

The results are as follows:

The call succeeded.

---------

Private Declare Function shellexecute Lib "Shell32.dll" Alias "Shellexecutea" (ByVal hwnd as Long, ByVal lpoperation as St Ring, ByVal lpfile As String, ByVal lpparameters as String, ByVal lpdirectory as String, ByVal nShowCmd as long) as long
ShellExecute 0, "Open", "Python.exe", "C:\Mypython.py", "", 1
End Sub
Please refer to above!
-----------
Description of the problem:

With Python's powerful network capabilities and rich open source components and a good framework for developing Windows Form programs in C #, Python and C # Hybrid programming can effectively combine the strengths of both to quickly develop products.

However, the transmission of information/data between the two has become a primary problem.

Solution Ideas:

It is a preferred technique to facilitate object conversion between the two (the introduction of JSON is no longer described, and reference is made to [1]). Now that we've chosen to use JSON as a message-passing format, there are two scenarios in which we can deal with this problem:

I. Passing a JSON string through an intermediate file

In Python, you assemble the object that you want to pass to C # into a list, convert it to a JSON string, write the string to the file, and then read the file in the C # side and deserialize it into the list of objects.

Words not much to say, directly on the code:

Python-Side code:

Note: Only the core code is posted here. [2] You can refer to how to convert a custom Python to a JSON string.

C # side code:

Second, pass the JSON string through the return value

The JSON string that converts the list of objects to the Python side directly returns, captures the return value directly on the C # side, and deserializes it into the list of objects, with the following code:

Python side

C # End

This approach omits read and write operations to intermediate files, which is less time-and-space overhead for the program to run.

Reference documents:

"1" Introduction to JSON http://www.json.org/json-zh.html

"2" uses JSON as an intermediate file for object conversions when mixed programming with Python and C # http://www.cnblogs.com/chaosimple/p/4035693.html

"3" best-return a value from a Python script http://stackoverflow.com/questions/18231415/ Best-way-to-return-a-value-from-a-python-script

-----------Ython Connection operation of various databases

Summary:

Write scripts with Python for some time, often operate the database (MySQL), now to organize the operation of various types of databases, such as the following new parameters will be added, and gradually improve.

One, python operation MySQL: Details see: here

Mac installation: HTTP://SOURCEFORGE.NET/PROJECTS/MYSQL-PYTHON/?SOURCE=DLP and sudo python setup.py build

"Apt-get Install Python-mysqldb"

#!/bin/env python#-*-encoding:utf-8-*-#------------------------------------------------------------------------ -------# purpose:example for python_to_mysql# author:zhoujy# created:2013-06-14# update:2013-06-14#- ------------------------------------------------------------------------------ImportMySQLdbImport os# Establish a connection to the database system,format#conn = MySQLdb.connect (host= ' localhost ', user= ' root ', passwd= ' 123456 ', db= ' test ', port=3306,charset= ' UTF8 ') #指定配置文件, Determine the directory, or write the absolute path CWD = Os.path.realpath (Os.path.dirname (__file__)) db_conf = Os.path.join (CWD, ' db.conf ') conn = MySQLdb.connect (Read_default_file=db_conf,host= ' localhost ', db= ' test ', port=3306,charset= ' utf8 ') #要执行的sql语句query = ' Select id from t1 ' #获取操作游标cursor =conn.cursor ()#执行SQLcursor.execute (query)#获取一条记录, each record is returned as a tuple, returns 3, and the cursor refers to the 2nd record. RESULT1 =Cursor.fetchone ()For i in Result1:print i# returns the number of rows affected printCursor.rowcount#获取指定数量记录, each record is returned as a tuple, returns 1, 2, the cursor starts with the 2nd record, and the cursor refers to the 4th record. RESULT2 =Cursor.fetchmany (2)For I in Result2:for II in I:print ii# gets all records, each record is returned as a tuple, returns 3,4,7,6, and the cursor starts from the 4th record to the end. RESULT3 =Cursor.fetchall ()For I in Result3:for II in I:print ii# get all records, each record as a tuple return, return 3,4,7,6, cursor from 1th record start # reset cursor position, 0 offset, Mode=absolute | Relative, default is relativeCursor.scroll(0,Mode= ' absolute ') RESULT3 = Cursor.fetchall () for I in Result3:for II in I:print ii# the following 2 ways to insert data into the database: # (one) for I in Range (10,20): Query2 = ' INSERT into T1 values ("%d", now ()) '%i cursor.execute (query2) #提交 Conn.rollback () # ( rows = []for i in Range (10,20): Rows.append (i) Query2 = ' Insert to T1 values ("%s", now ()) ' #executemany 2 parameters, the 2nd parameter is a variable.Cursor.executemany (query2,rows)#提交conn. Commit () #选择数据库query3 = ' Select id from dba_hospital ' #重新选择数据库conn.select_db(' Chushihua ') cursor.execute (query3) RESULT4 = Cursor.fetchall () for I in Result4:for II in I:print ii# does not define query, straight Follow-up:
Cursor.execute ("Set session binlog_format= ' mixed '") #关闭游标, releasing resourcescursor.close ()"' +------+---------------------+| ID | Modifyt |+------+---------------------+| 3 | 2010-01-01 00:00:00 | | 1 | 2010-01-01 00:00:00 | | 2 | 2010-01-01 00:00:00 | | 3 | 2010-01-01 00:00:00 | | 4 | 2013-06-04 17:04:54 | | 7 | 2013-06-04 17:05:36 | | 6 | 2013-06-04 17:05:17 |+------+---------------------+ "

Note: In the script, the password written in the script is very easy to expose, so that you can use a configuration file to save the password, such as db.conf:

[client]user=rootpassword=123456

Two, python operation MongoDB: Details see here and here and here

#!/bin/env python#-*-encoding:utf-8-*-#------------------------------------------------------------------------ -------# purpose:example for python_to_mongodb# author:zhoujy# created:2013-06-14# update:2013-06-14 #-------------------------------------------------------------------------------ImportPymongoImport os# Establish a connection to the database system, and when the connection is created,specify host and port parametersconn =Pymongo. Connection(host= ' 127.0.0.1 ', port=27017) #admin database with account number, connection-authentication-switch Library Db_auth = Conn.admindb_auth.Authenticate(' sa ', ' sa ') #连接数据库db = conn.abc# Connection table collection = db.stu# View all table namesdb.collection_names ()#print db.collection_names () #访问表的数据, specify column item =Collection.find({},{"sname": 1, "course": 1, "_id": 0}) for rows in Item:print rows.values () #访问表的一行数据printCollection.find_one ()#得到所有的列for rows in Collection.find_one (): Print rows# InsertCollection.insert({"Sno": "Sname": "JL", "course": {"D": +, "s": ()}) #或u = Dict (sno=102,sname= ' zjjj ', course={"D": +, "s": 85}) Collection.insert (U) #得到行数printCollection.find (). Count ()Print Collection.find ({"sno":) #排序, according to the value of a column. Pymongo. Descending: Reverse; Pymongo. Ascending: Ascending. Follow SNO Reverse item =Collection.find (). Sort(' Sno ', Pymongo. Descending) for rows in Item:print rows.values () #多列排序item = Collection.find ().Sort([' Sno ', Pymongo. Descending), (' A ', Pymongo. Ascending)]) #更新, the first parameter is the condition, the second parameter is the update operation, $set,%inc, $push, $ne, $addToSet, $rename, etc.collection.update({"Sno": 100},{"$set": {"sno": 101}}) #更新多行和多列Collection.Update({"Sno": 102},{"$set": {"sno": "Sname": "SSSS"}},multi=true#删除, the first parameter is the condition, and the second parameter is the delete operation.Collection.Remove({"Sno": 101}) ' SNO: study number; sname: Name; course: Subject Db.stu.insert ({"Sno": 1, "sname": "Zhang San", "course": {"A": "A", "C": "B": "D" ": Db.stu.insert," E ": [+]}) ({" Sno ": 2," sname ":" John Doe "," course ": {" A ":" All "," B ": $," X ": +," Y ": +," Z ": 95}) Db.stu.insert ({"Sno": 3, "sname": "Zhao Wu", "course": {"A": +, "B": "H", "F": $, "G": +/--) Db.stu.insert ({"Sno": 4, " Sname ":" Zhoujy "," course ": {" A ": +," B ": $," C ":----" T ": 94," Y ":"}} "Db.stu.insert ({" Sno ": 5," sname ":" abc "," Course ": { "A": All, "B": +, "Z": +, "G": Si, "H": (+)}) Db.stu.insert ({"Sno": 6, "sname": "Yang Six", "course": {"A": +, "U": +, "C":, "R": 75 , "n": Db.stu.insert}) ({"Sno": 7, "sname": "Chen er", "course": {"A": Up, "M":--"n": "S": +, "K": "MM") Db.stu.insert ({" Sno ": 8," sname ":" Zhoujj "," course ": {" P ": All," B ":" N "," J ":," K ": (-)," L ": +}) Db.stu.insert ({" Sno ": 9," sname ":" CCC "," Course ": {" Q ": +," B ":", "C": +, "V":, "U": 85}) "

Calculate the number of collections in a MongoDB document:

Import Pymongoconn   = Pymongo. Connection (host= ' 127.0.0.1 ', port=27017) db = Conn.abc    #abc文档for tb_name in Db.collection_names ():     #循环出各集合名    count = Db[tb_name].count ()            #计算各集合的数量    if Count > 2:                                 #过滤条件        print Tb_name + ': ' + str (Count) ' Con n   = Pymongo. Connection (host= ' 127.0.0.1 ', port=27017) db = Conn.abcfor tb_name in Db.collection_names ():    print Tb_name + ': '     exec (' print ' + ' db. ') +tb_name+ '. Count () ')      #变量当集合的处理方式ORconn   = Pymongo. Connection (host= ' 127.0.0.1 ', port=27017) db = Conn.abcfor tb_name in Db.collection_names ():    Mon_dic=db.command (" Collstats ", tb_name)      #以字典形式返回    print mon_dic.get (' ns '), Mon_dic.get (' count ')"

updatetime: 2015-06-30

After MongoDB has been upgraded to 3.0, the connection with Python will be faulted:

Pymongo.errors.OperationFailure:command SON ([' Authenticate ', 1), (' User ', U ' dba '), (' Nonce ', U ' 8c7842b068e14d3 '), (' Key ', U ' 584ec63f1cdfd8525ce33d99cd269c2c ')]) Failed:auth failed

Indicates that the authentication failed, after MongoDB upgrade, to the user's encryption method changed. Then upgrade the Pymongo.

[Email protected]:~$ sudo pip install Pymongo--upgrade[sudo] password for zhoujy: ... Successfully installed pymongocleaning up ...

Upgrade success, if not installed Pip, see here: http://www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/

After ubuntu10.10:

Older versions prior to ubuntu10.10:

After the upgrade succeeds, continue with the Python script or error:

Attributeerror: ' Module ' object has no attribute ' Connection '

Said no Connection, Pymongo after the upgrade is not supported, read the manual, found that mongoclient to replace the Connection. to modify a script:

Conn   = Pymongo.  Connection(host= ' 127.0.0.1 ', port=27017) changed to conn   = Pymongo.  Mongoclient(host= ' 127.0.0.1 ', port=27017)

Finally execute python, normal.

third, Python operation Redis: Details see here and here/here; Cluster Connection

#!/bin/env python#-*-encoding:utf-8-*-#------------------------------------------------------------------------ -------# purpose:example for python_to_mongodb# author:zhoujy# created:2013-06-14# update:2013-06-14 #-------------------------------------------------------------------------------ImportRedisf = open (' Aa.txt ') while true:line = F.readline (). Strip (). Split (' # ') if line = = ["]: Break username,pwd , Email = line# print Name.strip (), Pwd.strip (), Email.strip ()rc = Redis. Strictredis (host= ' 127.0.0.1 ', port=6379,db=15)    Rc.hset(' Name: ' + UserName, ' email ', email)Rc.hset(' Name: ' + UserName, ' Password ', PWD) f.close () AllUser =Rc.keys(' * ') #print alluserprint "=================================== read out the data stored in ===================================" for user In Alluser:print ' # '. Join ((User.split (': ') [1],rc.hget (User, ' Password '), rc.hget (user, ' Email '))

A pipeline please look: here

Four, python operation Memcache: see here and here for details

Import Memcache
MC = Memcache. Client ([' 127.0.0.1:11211 '],debug=1)
#!/usr/bin/env Python#coding=utf-8import MysqldbimportmemcacheImport Sysimport timedef get_data (mysql_conn): # nn = raw_input ("Press string Name:")mc = memcache. Client ([' 127.0.0.1:11211 '],debug=1)T1 =time.time () value =Mc.get(' Zhoujinyia ') if value = = None:t1 = Time.time () print T1 query = "SELECT Company,email,sex,addr        ESS from uc_user_offline where realname = ' Zhoujinyia ' "cursor= mysql_conn.cursor () cursor.execute (query) item = Cursor.fetchone () t2 = time.time () print t2 t = round (T2-T1) print "from MySQL Cos T%s sec "%t Print itemMc.set(' Zhoujinyia ', item,60) else:t2 = Time.time () t=round (t2-t1) print "From Memcache cost%s sec"%t Print Valueif __name__ = = ' __main__ ': Mysql_conn = MySQLdb.connect (host= ' 127.0.0.1 ', user= ' root ', passwd= ' 123456 ', db= ' member ', port=3306,charset= ' UTF8 ') get_data (mysql_conn)


The above describes some Python connection database, the red part is a key part of the connection operation, most of the operations are not listed, specific please see the official website.

Calling Python in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.