瀏覽代碼

1、进行封装类;

scbc.sat2 5 年之前
父節點
當前提交
eb54df1eb9

+ 36 - 0
RunPython/RunPython - 2019.sln

@@ -0,0 +1,36 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.29418.71
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RunPython", "RunPython\RunPython.vcxproj", "{92FC4676-AAFC-4568-93EE-849029E5381D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test\test.vcxproj", "{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		DeubgExe|Win32 = DeubgExe|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.Debug|Win32.Build.0 = Debug|Win32
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.DeubgExe|Win32.ActiveCfg = DeubgExe|Win32
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.DeubgExe|Win32.Build.0 = DeubgExe|Win32
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.Release|Win32.ActiveCfg = Release|Win32
+		{92FC4676-AAFC-4568-93EE-849029E5381D}.Release|Win32.Build.0 = Release|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.Debug|Win32.ActiveCfg = Debug|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.Debug|Win32.Build.0 = Debug|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.DeubgExe|Win32.ActiveCfg = Debug|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.DeubgExe|Win32.Build.0 = Debug|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.Release|Win32.ActiveCfg = Release|Win32
+		{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {78E85C45-0F3B-46BE-94FA-C6544A4C5E0B}
+	EndGlobalSection
+EndGlobal

+ 34 - 0
RunPython/RunPython/PythonHelper.h

@@ -1,8 +1,42 @@
+#ifndef __PYTHON_HELPER__
+#define __PYTHON_HELPER__
+
 #pragma once
 
+#define THREAD_SIZE 100
+
+// 工作参数,用于工作者线程;
+typedef struct __WORK_PARAMTER__ 
+{
+	HANDLE			hThread;					// 事件句柄;
+	HANDLE			hEvent;						// 线程事件;
+	BOOL			bStatus;					// 线程状态;
+	TCHAR			szScriptPath[MAX_PATH];		// 脚本路径;
+	TCHAR			szLogPath[MAX_PATH];		// 日志路径;	
+	// 重定向标准输出和标准错误;
+	HANDLE			hStdOutRead;
+	HANDLE			hStdOutWrite;
+	HANDLE			hStdErroWrite;
+}WorkParamter, *pWorkParamter;
+
 class CPythonHelper
 {
 public:
 	CPythonHelper(void);
 	~CPythonHelper(void);
+
+public:
+	// 添加脚本;
+	// strScript:	脚本路径;
+	// strLogPath:	日志路径;
+	// nRunType:	运行方式, 0=嵌入C++ 1=子进程运行;
+	bool AddPythonScript(std::string strScript, std::string strLogPath, int nRunType = 0);
+	// 停止脚本运行;
+	void StopScript();
+
+protected:
+	// 工作者线程函数;
+	static DWORD WINAPI _WorkerThread(LPVOID lpParam);
 };
+
+#endif //__PYTHON_HELPER__

+ 8 - 0
RunPython/RunPython/RunPython.vcproj

@@ -257,6 +257,10 @@
 				RelativePath=".\RunPython.cpp"
 				>
 			</File>
+			<File
+				RelativePath=".\ScriptExecutor.cpp"
+				>
+			</File>
 			<File
 				RelativePath=".\stdafx.cpp"
 				>
@@ -303,6 +307,10 @@
 				RelativePath=".\RunPython.h"
 				>
 			</File>
+			<File
+				RelativePath=".\ScriptExecutor.h"
+				>
+			</File>
 			<File
 				RelativePath=".\stdafx.h"
 				>

+ 158 - 0
RunPython/RunPython/RunPython.vcxproj

@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="DeubgExe|Win32">
+      <Configuration>DeubgExe</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{92FC4676-AAFC-4568-93EE-849029E5381D}</ProjectGuid>
+    <RootNamespace>RunPython</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DeubgExe|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <PlatformToolset>v142</PlatformToolset>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <PlatformToolset>v142</PlatformToolset>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <PlatformToolset>v142</PlatformToolset>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='DeubgExe|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>16.0.29403.142</_ProjectFileVersion>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <OutDir>..\..\..\..\bin\$(SolutionName)\</OutDir>
+    <IntDir>$(OutDir)$(ProjectName)\$(Configuration)\</IntDir>
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <OutDir>..\..\..\..\bin\$(SolutionName)\</OutDir>
+    <IntDir>$(OutDir)$(ProjectName)\$(Configuration)\</IntDir>
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DeubgExe|Win32'">
+    <OutDir>..\..\..\..\bin\$(SolutionName)\</OutDir>
+    <IntDir>$(OutDir)$(ProjectName)\$(Configuration)\</IntDir>
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>C:\Python27\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;RUNPYTHON_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <AdditionalLibraryDirectories>C:\Python27\libs;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Windows</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <AdditionalIncludeDirectories>C:\Python27\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;RUNPYTHON_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <AdditionalLibraryDirectories>C:\Python27\libs;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Windows</SubSystem>
+      <OptimizeReferences>true</OptimizeReferences>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DeubgExe|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>C:\Python27\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;RUNPYTHON_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <AdditionalLibraryDirectories>C:\Python27\libs;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="PythonHelper.cpp" />
+    <ClCompile Include="RunPython.cpp" />
+    <ClCompile Include="ScriptExecutor.cpp" />
+    <ClCompile Include="stdafx.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DeubgExe|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="PythonHelper.h" />
+    <ClInclude Include="Resource.h" />
+    <ClInclude Include="RunPython.h" />
+    <ClInclude Include="ScriptExecutor.h" />
+    <ClInclude Include="stdafx.h" />
+    <ClInclude Include="targetver.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="RunPython.rc" />
+  </ItemGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

+ 59 - 0
RunPython/RunPython/RunPython.vcxproj.filters

@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="源文件">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="头文件">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="资源文件">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="PythonHelper.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="RunPython.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="ScriptExecutor.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="stdafx.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="PythonHelper.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="Resource.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="RunPython.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="ScriptExecutor.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="stdafx.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="targetver.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="RunPython.rc">
+      <Filter>资源文件</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+</Project>

+ 291 - 0
RunPython/RunPython/ScriptExecutor.cpp

@@ -0,0 +1,291 @@
+#include "StdAfx.h"
+#include "ScriptExecutor.h"
+
+CScriptExecutor::CScriptExecutor(void)
+{
+}
+
+CScriptExecutor::~CScriptExecutor(void)
+{
+}
+
+DWORD __stdcall CScriptExecutor::_WorkerThread(LPVOID lpParam)
+{
+	return 0;
+}
+
+int CScriptExecutor::RedirectStdout(STARTUPINFO &si)
+{
+	SECURITY_ATTRIBUTES sa;
+	sa.bInheritHandle = TRUE;
+	sa.lpSecurityDescriptor = NULL;
+	sa.nLength = sizeof(sa);
+
+	// 创建stdout的管道;
+	if (!CreatePipe(&m_hStdOutRead, &m_hStdOutWrite, &sa, 0))
+	{
+		printf("Error:创建stdout管道失败\n");
+		return -1;
+	}
+
+	// 创建stderr的管道,由于stderr一般就是stdout,直接复制句柄;
+	if (!DuplicateHandle(GetCurrentProcess(), m_hStdOutWrite, GetCurrentProcess(), &m_hStdErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS))
+	{
+		printf("创建stderr管道失败\n");
+		return -2;
+	}
+
+	si.dwFlags |= STARTF_USESTDHANDLES;
+	// 将子进程的stdout输出到句柄hStdOutWrite;
+	si.hStdOutput = m_hStdOutWrite;
+	// 将子进程的stderr输出到句柄hStdErrWrite;
+	si.hStdError = m_hStdErrorWrite;
+}
+
+void CScriptExecutor::CatchPythonException()
+{
+	if (!Py_IsInitialized())
+	{
+		printf("Error:未初始化Python环境\n");
+		return;
+	}
+
+	if (!PyErr_Occurred())
+	{
+		printf("Error:没有异常产生\n");
+		return;
+	}
+
+	// 捕获异常;
+	const char* pszErrMsg = NULL;
+	TCHAR* pszTraceback = NULL;
+
+	PyObject* pPyType = NULL;
+	PyObject* pPyValue = NULL;
+	PyObject* pPyTraceback = NULL;
+	// 非控制台,使用PyErr_Fetch捕获异常;
+	PyErr_Fetch(&pPyType, &pPyValue, &pPyTraceback);
+	PyErr_NormalizeException(&pPyType, &pPyValue, &pPyTraceback); // 可有可无,不影响获取异常;
+	if (pPyValue)
+	{
+		PyObject* pPyStr = PyObject_Str(pPyValue);
+		if (PyString_Check(pPyStr))
+		{
+			pszErrMsg = PyString_AsString(pPyStr);
+			if (pszErrMsg)
+				printf("Error Info=>%s\n", pszErrMsg);
+
+			if (pPyTraceback)
+			{
+				PyObject* pPyTraceModule = PyImport_ImportModule("traceback");
+				if (!pPyTraceModule)
+				{
+					printf("Error:导入traceback模块失败\n");
+					return;
+				}
+#if 1
+				PyObject* pPyModuleDict = PyModule_GetDict(pPyTraceModule);
+				if (pPyModuleDict)
+				{
+					PyObject* pPyFunc = PyDict_GetItemString(pPyModuleDict, "format_exception");
+					if (!pPyFunc || !PyCallable_Check(pPyFunc))
+					{
+						printf("Error:加载format_exception失败\n");
+						return;
+					}
+
+					PyObject* pErroList = PyObject_CallFunctionObjArgs(pPyFunc, pPyType, pPyValue, pPyTraceback, NULL);
+					if (pErroList)
+					{
+						int nSize = PyList_Size(pErroList);
+						for (int i = 0; i < nSize; i++)
+						{
+							pszErrMsg = PyString_AsString(PyList_GetItem(pErroList, i));
+							printf("%s", pszErrMsg);
+						}
+					}
+					Py_DECREF(pErroList);
+				}
+
+				Py_XDECREF(pPyTraceModule);
+#else // 不细分Item;
+				PyObject* pPyFunc = PyObject_GetAttrString(pPyTraceModule, "format_exception");
+				if (!pPyFunc || !PyCallable_Check(pPyFunc))
+				{
+					printf("Error:加载format_exception失败\n");
+					return;
+				}
+
+				PyObject* pPyResult = PyObject_CallFunctionObjArgs(pPyFunc, pPyType, pPyValue, pPyTraceback, NULL);
+				pPyStr = PyObject_Str(pPyResult);
+				pszErrMsg = PyString_AsString(pPyStr);
+				if (pszErrMsg)
+					printf("%s\n", pszErrMsg);
+
+				Py_DECREF(pPyResult);
+				Py_XDECREF(pPyTraceModule);
+#endif
+			}
+		}
+	}
+
+	Py_XDECREF(pPyType);
+	Py_XDECREF(pPyValue);
+	Py_XDECREF(pPyTraceback);
+}
+
+int CScriptExecutor::RunEmbeddedScript()
+{
+	// 参数有效性判断;
+	if (!PathFileExists(m_szScriptPath))
+	{
+		printf("Error:脚本文件不存在\n");
+		return -1;
+	}
+
+	// 初始化Python环境;
+	Py_Initialize();
+	if (!Py_IsInitialized())
+	{
+		printf("Error:初始化Python环境失败\n");
+		return -2;
+	}
+
+	// 解析脚本路径和脚本名称;
+	std::string scriptdir;
+	TCHAR szDrive[_MAX_DRIVE] = { 0 };
+	TCHAR szDir[_MAX_DIR] = { 0 };
+	TCHAR szExt[_MAX_EXT] = { 0 };
+	TCHAR szFilename[_MAX_FNAME] = { 0 };
+	TCHAR szScriptDir[MAX_PATH] = { 0 };
+	_tsplitpath_s(m_szScriptPath, szDrive, szDir, szFilename, szExt);
+	_stprintf_s(szScriptDir, _T("%s%s"), szDrive, szDir);
+	// 缓存一份路径;
+	scriptdir = szScriptDir;
+	// 将'\'转换成'/', Python才设置运行目录成功;
+	int len = _tcslen(szScriptDir);
+	for (int i = 0; i < len; i++)
+	{
+		if (szScriptDir[i] == '\\')
+			szScriptDir[i] = '/';
+	}
+	//szScriptDir[len-1] = '\0';
+
+	TCHAR szExecuteDir[MAX_PATH] = { 0 };
+	_stprintf_s(szExecuteDir, _T("sys.path.append(\"%s\")"), szScriptDir);
+	// 添加系统模块,并指定当前脚本路径为运行路径;
+	PyRun_SimpleString("import sys");
+	PyRun_SimpleString(szExecuteDir);
+	// 运行额外的语句,一般用于传递命令行参数;
+	if (_tcslen(m_szExtraSentence))
+		PyRun_SimpleString(m_szExtraSentence);
+
+	// 注意:脚本名称尽量不要与系统目录其他py文件相同;
+	// 导入脚本,以脚本名称为模块名加载;
+	PyObject* pModuleObj = PyImport_ImportModule(szFilename);
+	if (!pModuleObj)
+	{
+		printf("Error:加载脚本模块失败\n");
+		Py_Finalize();
+		return -3;
+	}
+
+	// 获取脚本的主函数名称(规定所有脚本的主函数名为main)
+	// 加载函数:注意,如果目录下有同名的脚本文件,可能会加载失败;
+	PyObject* pFunction = PyObject_GetAttrString(pModuleObj, "main");
+	if (!pFunction || !PyCallable_Check(pFunction))
+	{
+		printf("Error:加载函数失败\n");
+		Py_Finalize();
+		return -4;
+	}
+
+	// 执行main函数;
+	PyObject* pResult = PyObject_CallObject(pFunction, NULL);
+	if (!pResult)
+	{
+		printf("Error:执行函数失败\n");
+		CatchPythonException();
+		Py_Finalize();
+		return -5;
+	}
+	Py_DECREF(pResult);
+
+	Py_Finalize();
+
+	return 0;
+}
+
+int CScriptExecutor::RunScripProcess()
+{
+	if (!PathFileExists(m_szScriptPath))
+	{
+		printf("参数无效\n");
+		return -1;
+	}
+
+	// 获取Python27进程目录;
+	TCHAR szPython27Dir[MAX_PATH] = { 0 };
+	TCHAR szPython27Exe[MAX_PATH] = { 0 };
+	if (!Python27Dir(szPython27Dir, MAX_PATH))
+	{
+		printf("获取Python27目录失败\n");
+		return -2;
+	}
+	_stprintf_s(szPython27Exe, _T("%spython.exe"), szPython27Dir);
+
+	STARTUPINFO si;
+	::memset(&si, 0, sizeof(si));
+	si.cb = sizeof(si);
+
+	PROCESS_INFORMATION pi;
+	::memset(&pi, 0, sizeof(pi));
+
+	TCHAR szCommandLine[MAX_PATH] = { 0 };
+	if (_tcslen(m_szExtraSentence))
+		_stprintf_s(szCommandLine, _T("python -W ignore %s %s"), m_szScriptPath, m_szExtraSentence);
+	else
+		_stprintf_s(szCommandLine, _T("python -W ignore %s"), m_szScriptPath);
+
+	// 启动子进程;
+	if (!CreateProcess(
+		NULL,			// No module name (use command line)
+		szCommandLine,			// Command line
+		NULL,					// Process handle not inheritable
+		NULL,					// Thread handle not inheritable
+		FALSE,					// Set handle inheritance to TRUE
+		0,						// No creation flags
+		NULL,					// Use parent's environment block
+		NULL,					// Use parent's starting directory 
+		&si,					// Pointer to STARTUPINFO structure
+		&pi)					// Pointer to PROCESS_INFORMATION structure
+		)
+	{
+		printf("CreateProcess failed (%d).\n", GetLastError());
+		return -3;
+	}
+
+	// Wait until child process exits.
+	WaitForSingleObject(pi.hProcess, INFINITE);
+
+	// Close process and thread handles. 
+	CloseHandle(pi.hProcess);
+	CloseHandle(pi.hThread);
+
+	return 0;
+}
+
+void CScriptExecutor::InitScript(std::string strScript, std::string strLogPath, std::string strScriptCmd, int nRunType)
+{
+
+}
+
+bool CScriptExecutor::StartScript()
+{
+	return false;
+}
+
+bool CScriptExecutor::StopScript()
+{
+	return false;
+}

+ 45 - 0
RunPython/RunPython/ScriptExecutor.h

@@ -0,0 +1,45 @@
+#ifndef __SCRIPT_EXECUTOR__
+#define __SCRIPT_EXECUTOR__
+
+#pragma once
+
+class CScriptExecutor
+{
+public:
+	CScriptExecutor(void);
+	~CScriptExecutor(void);
+
+protected:
+	HANDLE			m_hThread;						// 事件句柄;
+	HANDLE			m_hEvent;						// 线程事件;
+	BOOL			m_bStatus;						// 线程状态;
+	TCHAR			m_szScriptPath[MAX_PATH];		// 脚本路径;
+	TCHAR			m_szLogPath[MAX_PATH];			// 日志路径;	
+	TCHAR			m_szExtraSentence[MAX_PATH];	// 脚本命令行参数;
+	int				m_nRunType;
+	// 重定向标准输出和标准错误;
+	HANDLE			m_hStdOutRead;
+	HANDLE			m_hStdOutWrite;
+	HANDLE			m_hStdErrorWrite;
+
+protected:
+	// 工作者线程函数;
+	static DWORD WINAPI _WorkerThread(LPVOID lpParam);
+	// 重定向标准输出;
+	int RedirectStdout(STARTUPINFO& si);
+	// 获取Python异常;
+	void CatchPythonException();
+	// 运行嵌入的脚本;
+	int RunEmbeddedScript();
+	// 运行脚本进程;
+	int RunScripProcess();
+	
+public:
+	void InitScript(std::string strScript, std::string strLogPath, std::string strScriptCmd, int nRunType = 0);
+	// 运行脚本;
+	bool StartScript();
+	// 停止脚本;
+	bool StopScript();
+};
+
+#endif // __SCRIPT_EXECUTOR__

+ 147 - 0
RunPython/test/test.vcxproj

@@ -0,0 +1,147 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{332DAF3B-C481-4F4F-8628-FBF1095BE4C2}</ProjectGuid>
+    <RootNamespace>test</RootNamespace>
+    <Keyword>MFCProj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <PlatformToolset>v142</PlatformToolset>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <CharacterSet>Unicode</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <PlatformToolset>v142</PlatformToolset>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>16.0.29403.142</_ProjectFileVersion>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <OutDir>..\..\..\..\bin\$(SolutionName)\</OutDir>
+    <IntDir>$(OutDir)$(ProjectName)\$(Configuration)\</IntDir>
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <OutDir>..\..\..\..\bin\$(SolutionName)\</OutDir>
+    <IntDir>$(OutDir)$(ProjectName)\$(Configuration)\</IntDir>
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Midl>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MkTypLibCompatible>false</MkTypLibCompatible>
+      <ValidateAllParameters>true</ValidateAllParameters>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <ResourceCompile>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <Culture>0x0804</Culture>
+      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ResourceCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Windows</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Midl>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MkTypLibCompatible>false</MkTypLibCompatible>
+      <ValidateAllParameters>true</ValidateAllParameters>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>false</MinimalRebuild>
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <ResourceCompile>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <Culture>0x0804</Culture>
+      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ResourceCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Windows</SubSystem>
+      <OptimizeReferences>true</OptimizeReferences>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="stdafx.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="test.cpp" />
+    <ClCompile Include="testDlg.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Resource.h" />
+    <ClInclude Include="stdafx.h" />
+    <ClInclude Include="targetver.h" />
+    <ClInclude Include="test.h" />
+    <ClInclude Include="testDlg.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <Image Include="res\test.ico" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="test.rc" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="res\test.rc2" />
+  </ItemGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+  <ProjectExtensions>
+    <VisualStudio>
+      <UserProperties RESOURCE_FILE="test.rc" />
+    </VisualStudio>
+  </ProjectExtensions>
+</Project>

+ 63 - 0
RunPython/test/test.vcxproj.filters

@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="源文件">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="头文件">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="资源文件">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="stdafx.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="test.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="testDlg.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Resource.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="stdafx.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="targetver.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="test.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="testDlg.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <Image Include="res\test.ico">
+      <Filter>资源文件</Filter>
+    </Image>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="test.rc">
+      <Filter>资源文件</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="res\test.rc2">
+      <Filter>资源文件</Filter>
+    </None>
+  </ItemGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+</Project>