您的位置:首页 > 编程语言 > C语言/C++

vs2010中C++调用python脚本并制作安装包

2013-01-10 20:00 926 查看
一、 准备工作

1. 安装visual studio 210。

2. 安装python编译环境,笔者版本为2.7.2。

3. 安装py2exe,用于给编写好的python打包。

二、编写python脚本程序

以下程序为笔者为学校的bbs写的登陆脚本LilyLogin.py,输入为用户名和密码,返回一段cookie字符串:

import httplib,urllib
import re
import random

def Login(userid,password):
params=urllib.urlencode({'id':userid,'pw':password});
headers={'Referer':'http://bbs.nju.edu.cn/cache_bbsleft.htm'}
#userdir是随机生成每个用户的线程,如‘/vd89905’
userdir='/vd'+str(random.randint(100,100000))

conn=httplib.HTTPConnection('bbs.nju.edu.cn')
conn.request('POST',userdir+'/bbslogin?type=2',params,headers)
response=conn.getresponse()

msg=response.read()
if response.status==200 and response.reason=='OK':
print '>>>> login success!'

patt='\'(\d+)N'+userid+'\+(\d+)\''
cookieOrign=re.findall(patt,msg)
cookies=[]
#小百合设置对_U_NUM+2,对_U_KEY-2
cookies.append(str(int(cookieOrign[0][0])+2))
cookies.append(str(int(cookieOrign[0][1])-2))
cookie=' _U_NUM='+cookies[0]+'; _U_UID='\
+userid+'; _U_KEY='+cookies[1]+' FOOTKEY=; '
return cookie


三、利用py2exe为写好的python脚本打包

编写setup.py脚本:

import py2exe
from distutils.core import setup
setup(console=['LilyLogin.py'])


将setup.py和LilyLogin.py放到python的安装路径中(笔者的为C:\Program Files\python)。

在cmd的C:\Program Files\python路径下运行:

python setup.py py2exe


这时会在安装目录下生成dist和build文件夹,dist文件夹中就是我们所需要的包,如下图:



红色方框的为python运行时的库文件,打包后默认文件名为library.zip,需要改成python27.zip,否则vs最终打包后的程序无法调用python库

四、C++调用python脚本中的函数

在编写C++程序之前,需要在项目属性中设置对python头文件和库函数位置的引用,将python安装目录下的include文件夹和libs文件夹添加到vc++目录,即下图中加粗的位置:



下面的C++程序主要是为了调用LilyLogin.py中的Login函数,返回值代表调用是否成功,参数为用户名、密码以及返回cookie的指针。

#include <iostream>
#include <string>
#include <Python.h> // this is in <python-install-path>/include folder
using namespace std;

bool LogIn(string userid,string password,string* cookie)
{
string filename="LilyLogin";
string methodname="Login";
PyObject *pyFileName=PyString_FromString(filename.c_str());
cout<<pyFileName<<endl;
PyErr_Clear();
PyObject *pyMod=PyImport_Import(pyFileName); //打包时调用失败,返回为空
cout<<"in function"<<endl;
cout<<pyMod<<endl;
if(pyMod) //if OK
{
//load function
PyObject *pyFunc = PyObject_GetAttrString(pyMod, methodname.c_str());
cout<<"python function loaded"<<endl;
if(pyFunc && PyCallable_Check(pyFunc))
{
PyObject *pyParams = PyTuple_New(2);
PyObject *pyUserid = PyString_FromString(userid.c_str());
PyObject *pyPassword = PyString_FromString(password.c_str());
PyTuple_SetItem(pyParams, 0, pyUserid);
PyTuple_SetItem(pyParams, 1, pyPassword);
// ok, call the function
PyObject *pyResult = PyObject_CallObject(pyFunc, pyParams);
if(pyResult)
{
cout<<"py result"<<endl;
*cookie=PyString_AsString(pyResult);
cout<<2<<endl;
return true;
}
}
}
return false;
}

int main()
{
string filename="LilyLogin";
string methodname="Login";

string userid,password,cookie;
cout<<"userid:";
cin>>userid;
cout<<"password:";
cin>>password;

//first init
Py_NoSiteFlag = 1;

Py_Initialize();

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('.\')");

if(!Py_IsInitialized())
{
cout<<"python初始化失败!"<<endl;
return -1;
}

//PyRun_SimpleString("print 'hello world!'");
if(LogIn(userid,password,&cookie))
cout<<cookie<<endl;
else
cout<<"error....."<<endl;
// last fini!
Py_Finalize();

int x;
cin>>x;
return 0;
}


编译程序,生成exe文件,笔者生成的文件为pythonCpp.exe。

五、制作安装包

制作安装包是需要将dist文件夹中的文件以及C++编译后的exe、原python脚本(LilyLogin.py)一起添加进去,笔者的打包文件如下图(可能有些文件并不需要,读者可进行尝试):



制作完成,这下可以在未安装python的机器上运行程序了!

参考文献:

python+Cpp发布

[1] http://blog.csdn.net/yuucyf/article/details/5861724
[2] http://blog.csdn.net/youthwang/article/details/5016932
[3] http://www.freezhongzi.info/?p=92
[4] http://mail.python.org/pipermail/cplusplus-sig/2007-October/012680.html
VS2010 制作安装包

[5] http://blog.csdn.net/wondergdf/article/details/7529603
C++调用Python函数:

[6] http://blog.csdn.net/spvm1313113/article/details/5819297
[7] http://www.cnblogs.com/pzxbc/archive/2012/01/12/2320736.html
[8] http://docs.python.org/2/extending/embedding.html
[9] http://blog.sina.com.cn/s/blog_67ac78cf01010tlh.html (python返回list)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: