bcb6调用python的一种办法。
本质上就是通过管道,调用绿色版的python。抛砖引玉,希望能看到更好的办法。嘿嘿嘿嘿。
下载portable python1.1 2.61(此为绿色版,如果你真的这么用,需要精简一下,比如doc,txt以及没用的模块都删掉) 然运行得到一个PortablePython_1.1_py2.6.1文件夹。
太长了。改名为py261得了。放到你的程序目录下面,如下面代码
//---------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
bool __fastcall RunCmd(AnsiString cmd, TStringList * stringlist);
//---------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
bool __fastcall RunCmd(AnsiString cmd, TStringList * stringlist)
{
TMemoryStream *memstream = new TMemoryStream();
AnsiString rn = "\\r\\n";
PROCESS_INFORMATION proc;
STARTUPINFO start;
SECURITY_ATTRIBUTES sa;
long ret;
unsigned long lngBytesread;
HANDLE hReadPipe, hWritePipe;
char *strBuff = (char *)malloc(256);
if(strBuff == NULL)
{
return false;
}
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = NULL;
ret = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
if(ret == 0)
{
// 创建管道失败
return false;
}
memset(&start, 0x00, sizeof(STARTUPINFO));
start.cb = sizeof(STARTUPINFO);
start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
start.hStdOutput = hWritePipe;
start.hStdError = hWritePipe;
bool retc = CreateProcess(NULL, cmd.c_str(), NULL, NULL, true, 0, 0, NULL, &start,
&proc);
if(!retc)
{
return false;
}
CloseHandle(hWritePipe);
unsigned long len;
memstream->Position = 0;
while(true)
{
memset(strBuff, 0x00, 256);
GetFileSize(hReadPipe, &len);
ret = ReadFile(hReadPipe, strBuff, 256, &lngBytesread, NULL);
if(ret == 0)
{
break;
}
else
{
memstream->Write(strBuff, lngBytesread);
}
}
CloseHandle(proc.hProcess);
CloseHandle(proc.hThread);
CloseHandle(hReadPipe);
memstream->Position = 0;
free(strBuff);
stringlist->LoadFromStream(memstream);
memstream->Clear();
delete memstream;
return true;
}
//---------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String path ="D:\\Program Files\\Borland\\CBuilder6\\Projects\\python\\Py261\\App\";
TStringList *lst =new TStringList;
RunCmd (path+"python c:\\1.py",lst);
Memo1->Lines->Clear();
Memo1->Lines->AddStrings(lst);
delete lst;
}