VS2008环境下C++调用Python模块函数----一封邮件引发的关机

来源:互联网 发布:java shiro盐值加密 编辑:程序博客网 时间:2024/05/02 03:20

使用环境:

vs2008(C/C++)

Python 2.7

 

一、 基本配置

1、  配置头文件路径 D:\Python27\include。

添加包含(include)文件目录的方法:

         方法 1:[解决方案资源管理器]“项目->属性->配置属性->C/C++->常规->附加包含目录”。
         方法 2:[菜单]“工具->选项->项目和解决方案->C++ 目录”,选择对应平台,然后添加所需“包括文件”目录。

 

2、  配置依赖项路径:D:\Python27\libs。

添加库(Libs)文件目录:

         方法 1:[解决方案资源管理器]“项目->属性->配置属性->连接器->常规->附加库目录”。
         方法 2:[菜单]“工具->选项->项目和解决方案->C++ 目录”,选择对应平台,然后添加所需“库文件”目录。

 

3、  配置依赖性:python27_d.lib(注:此处有debug,所以要把C:\Python27\libs下的python27.lib改成python27_d.lib)

添加编译所需要(依赖)的 lib 文件的方法:

[解决方案资源管理器]“项目->属性->配置属性->连接器->输入->附加依赖项”里填写“python27_d.lib”,多个 lib 以空格隔开。(等同于“#pragma comment(lib, " python27_d.lib ") ”语句)

 

4、  注:右击项目->属性,配置属性->C/C++->预编译头,将“创建/使用预编译头”选项设为“不使用预编译头”

 

5、  如果使用C调用Python函数或解释器时,在添加了Include Directories和Library Directories等配置后,仍然编译错误:"LINK : fatal error LNK1104: cannot open file 'python27_d.lib'",可以在Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions添加MS_NO_COREDLL或Py_NO_ENABLE_SHARED,去掉_DEBUG,将没有效果。也可以在引用python.h头文件前添加#define MS_NO_COREDLL或#define Py_NO_ENABLE_SHARED。

 

二、 连接错误处理

在vs 2008 下 debug 模式出现链接问题 例如:

extmodule.obj : error LNK2019: unresolved external symbol __imp___Py_Dealloc referenced in function _PySwigObject_format

这主要是因为 Py_DEBUG/Py_TRACE_REFS 引起, 修改 Python\include 下的 pyconfig.h, object.h 两个文件就行了。

1. 修改 pyconfig.h

修改

#ifdef _DEBUG

# define Py_DEBUG

#endif

#ifdef _DEBUG

//# define Py_DEBUG

#endif

 

修改

# ifdef _DEBUG

# pragma comment(lib,"python24_d.lib")

# else

# pragma comment(lib,"python24.lib")

# endif

# ifdef _DEBUG

# pragma comment(lib,"python24.lib")

# else

# pragma comment(lib,"python24.lib")

# endif

 

2. object.h

修改

#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)

#define Py_TRACE_REFS

#endif

#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)

// #define Py_TRACE_REFS

#endif

 

【注意】c++在调用Python模块时,.py文件中不能带有汉字,即使是注释里面也不能写汉字,否则会出现PyImport_ImportModule返回值为NULL的错误。

 

三、  贴Python代码(以下代码保存文件为 REmail.py,方便下面的C代码调用

import poplib,getpass,string,sys,email,base64,os,cStringIO

def processMsg(entire_msg):

    body = ''

    msg = email.message_from_string(entire_msg)

    if msg.is_multipart():

        for part in msg.walk():

            if part.get_content_type() == 'text/plain':

                body = part.get_payload()

                break

            else:

                body = msg.get_payload(decode=True)

    else:

        body = msg.get_payload(decode=True)

    return body

 

def retrive_emails(pop3_server, user_name, passwd):

    #POP3

    pop_client = poplib.POP3(pop3_server)

    pop_client.user(user_name)

    pop_client.pass_(passwd)

   

    #print messages num

    num_messages, mbox_size = pop_client.stat()

    print 'there are %s new emails\n' % num_messages

    if num_messages == 0:

        pop_client.quit()

        #return

    print('num of messages %s' %str(num_messages))

   

    #mk folder

    folder_name = 'D:/Python27/email'

    if not os.path.exists(folder_name):

        os.mkdir(folder_name)

       

    for idx in range(num_messages-1,num_messages):         

        one_mail=pop_client.retr(idx+1)

        buf = cStringIO.StringIO()

        for j in one_mail[1]:           

            print >>buf,j 

        buf.seek(0)

       

        #parse mail content

        msg = email.message_from_file(buf)

        count=num_messages

        for part in msg.walk():

            contenttype = part.get_content_type()

            print('this is the %dth emai!\n'% (count))

            #count=count+1

            print('\npart:\n%s\n' % part)

            filename = part.get_filename() 

            print('filename : %s' % filename)

            print('contenttype : %s' % contenttype)

            if filename and (contenttype == 'application/octet-stream'):

                # save mail

                f = open("%s/mail%d.%s.attach"

                             %(folder_name, num_messages,filename), 'wb')

                #f.write(base64.b64decode(part.get_payload()))

                f.write(base64.decodestring(part.get_payload()))

                f.close()

            elif contenttype == 'text/plain':

                # save content

                #f   =   open("%s/mail%d.txt"   %(folder_name,num_messages),'wb')

                f   =   open("%s/mail.txt"   %(folder_name),'wb')

                #f.write(base64.decodestring(part.get_payload()))

                f.write(processMsg(part.get_payload()))

                f.close()

            elif contenttype == 'text/html':

                # save content

                f   =   open("%s/mail%d.html"   %(folder_name,num_messages),'wb')

                #f.write(processMsg(part.get_payload()))

                f.write(base64.decodestring(part.get_payload()))

                f.close()

            print('===========================================')

        buf.close()

        count=count+1

        if idx == 10:

            break

    pop_client.quit()

 

def rec126():

    pop3_server='pop.126.com'

    user_name='*************@126.com'

    passwd='*********'

    retrive_emails(pop3_server, user_name, passwd)

    #delete_mail(pop3_server, user_name, passwd)

def recSP():

    pop3_server='mail.starpointcomm.com'

    user_name='**********@starpointcomm.com'

    passwd='**********'

    retrive_emails(pop3_server, user_name, passwd)

def delete_mail(pop3_server, user_name, passwd):

    #POP3

    pop_client = poplib.POP3(pop3_server)

    pop_client.user(user_name)

    pop_client.pass_(passwd)

    print pop_client.stat()

    mailmax=pop_client.stat()[0]

    for i in range(mailmax-1,mailmax):

            pop_client.dele(i+1)

    print pop_client.stat()

    pop_client.quit()

   

def delete_mail_126():

    pop3_server='pop.126.com'

    user_name='*****@126.com'

    passwd='******'

    print ('delete function 126')

    pop_client = poplib.POP3(pop3_server)

    pop_client.user(user_name)

    pop_client.pass_(passwd)

    print ('delete function')

    print pop_client.stat()

    mailmax=pop_client.stat()[0]

    for i in range(mailmax-1,mailmax):

            pop_client.dele(i+1)

    print pop_client.stat()

    pop_client.quit()

 

if __name__ == '__main__': rec126()

 

 

四、贴C++代码

 

#include "Python.h"

#include "iostream"

#include “string”

#include "fstream"

#include "stdlib.h"

#include"Windows.h"

#define sleeptime 15*60     //十五分钟询问一次

using namespace std;

 

void shutdown()

{

       TOKEN_PRIVILEGES tkp;

    HANDLE hToken;

       if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

    {

    }

    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);//获得本地机唯一的标识

    tkp.PrivilegeCount = 1; 

    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); //调整获得的权限

    ExitWindowsEx(EWX_POWEROFF, 0);

}

 

int f_receive()

  

              int a=0;

              char buffer[256];

              int ws_shutdown_flag=0;

              char buffer1[]={"Shutdown"};

              PyObject *pModule, *pFunc, *pValue;

              Py_Initialize();   

        if (!Py_IsInitialized()) 

                     return -1; 

        PyRun_SimpleString("import sys");   

        PyRun_SimpleString("sys.path.append('D:\Python27')");   

        //import Module  

              pModule = PyImport_ImportModule("REmail");

          if (!pModule) {   

                cout<<"Can't import Module!\n"<<endl; 

                            system("pause");

                return -1;   

        }   

              pFunc=PyObject_GetAttrString(pModule, "rec126");  //也可以使用该函数得到函数对象

              pValue=PyObject_CallFunction(pFunc,NULL);      //通过函数对象执行函数

              cout<<PyLong_AsLong(pValue)<<endl;

        Py_Finalize();

             

              memset(buffer,0,sizeof(buffer)); 

              ifstream in("D:\\Python27\\email\\mail.txt"); 

       if (! in.is_open()) 

       {

                     cout << "Error opening file";

                     system("pause");

                     exit (1);

          } 

          in.getline (buffer,100); 

        cout << buffer << endl;

               in.close();

            cout<<buffer1<<endl;

          ws_shutdown_flag=memcmp(buffer,buffer1,sizeof(buffer1));

              if(ws_shutdown_flag==0)

              {    

                     cout<<"YES"<<endl;

                     Py_Initialize();   

                      if (!Py_IsInitialized()) 

                                   return -1; 

                     PyRun_SimpleString("import sys");   

                     PyRun_SimpleString("sys.path.append('D:\Python27')");

                     pModule = PyImport_ImportModule("REmail");

                      if (!pModule) {   

                cout<<"Can't import Module!\n"<<endl; 

                            system("pause");

                return -1;   

                     }

                     pFunc=PyObject_GetAttrString(pModule, "delete_mail_126");  //也可以使用该函数得到函数对象

                     pValue=PyObject_CallFunction(pFunc,NULL);

                     ofstream on("D:\\Python27\\email\\mail.txt");

                     on.open("D:\\Python27\\email\\mail.txt",ios::trunc,0);

                     on.close();

                     shutdown();

              }    

              else

              {

                     cout<<"NO"<<endl;

              }

              //system("pause");

        return 0;   

}

 

int main()

{

              while(1)

              {

                     Sleep(sleeptime*1000);

                     f_receive();

          }

              return 0;

}

0 0
原创粉丝点击