代码以及相关文件下载地址:
一、环境:
Windows 7
python 2.7
py2exe for python 2.7
Microsoft Visual Studio 2010
二、目标与原理:
1. 当C++执行数据库写入时,首先生成wordpart.txt文件
文件格式为:时间,词,词频 如:1340958642,奥特曼,15
2. C++利用CreateProcess创建进程,调用python编译而成的.exe文件写入数据库
python的参数命令为 --p [wordpart.txt的路径]
3. C++等待进程结束,进行后续操作
三、数据库的格式:
四、C++代码如下:
- #include "stdafx.h"
- #include <Windows.h>
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- char* wait = "" ;
- STARTUPINFO si = { sizeof(si) };
- PROCESS_INFORMATION pi;
- TCHAR szCommandLine[] = TEXT( "F:\\backup\\4\\dist\\writeCSV.exe --p F:\\wordpart.txt" );
- TCHAR szCmd[16] = {0};
- if(!CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
- {
- cout<< "fail!"<<GetLastError()<<endl;
- };
- WaitForSingleObject(pi.hProcess,INFINITE);
- cout<< "finished!";
- cin>>wait;
- return 0;
- }
五、python代码如下:
- #coding:utf-8
- import os, sys
- import MySQLdb
- def parseCSV(outPath):
- '''''parse the .csv/.out file'''
- wordGroups = []#return the [[word,time,frequency]...]
- outFile = open(outPath,'r')
- allLines = outFile.readlines()
- for eachline in allLines:
- lineParts = eachline.split(',')
- if len(lineParts) != 3:
- print 'wrong line format!'
- else:
- group = lineParts#[word, time, frequency]
- wordGroups.append(group)
- outFile.close()
- return wordGroups
- def writeToDB(wordGroups):
- conn = MySQLdb.connect(host = "localhost",user="root",\
- passwd = '111111',db='microblog',use_unicode=1\
- charset='utf8')
- cursor = conn.cursor()
- sql = "select word from word_frequency"
- count = cursor.execute(sql)
- rows = cursor.fetchall()
- wordAlreadyExists = rows[0:]["word"]#all words
- cursor.close()
- cursor = conn.cursor()
- for group in wordGroups:
- try:#in case of duplicated status
- sql = "insert into word_frequency(word,time,frequency) values (%s,%s,%d)"
- param = (group[0],group[1],group[2])
- cursor.execute(sql,param)
- except MySQLdb.Error, e:
- print(e)
- cursor.close()
- conn.commit()
- if __name__ == '__main__':
- '''''Write the c++ output .csv/.out to db
- example: --p [the path of .csv/.out]
- '''
- if len(sys.argv) < 3:
- #no argument, use the default path
- print 'wrong! --p [the path of .csv/.out]'
- elif sys.argv[1].startwith('--'):
- #parse sys.argv[2] execute the write statement
- option = sys.argv[1][2:]
- if option == 'p':
- outPath = sys.argv[2]
- else:
- print 'unknown option'
六、python 代码需要编译成.exe文件才能被C++调用执行,为此可使用py2exe工具
在cmd下运行python mysetup.py py2exe命令
mysetup.py如下:
- # setup.py
- from distutils.core import setup
- import py2exe
- setup(console=["writeCSV.py"])
生成dist文件夹,其中有writeCSV.exe
此时使用C++ 运行即可。
转载于:https://blog.51cto.com/asombroso/1174904