Просмотр исходного кода

增加C++进入Python脚本的入口类

Tang Hai 14 лет назад
Родитель
Сommit
45ee7d0e3c

+ 77 - 0
Src/Egametang/Python/PythonEntry.cc

@@ -0,0 +1,77 @@
+#include <boost/foreach.hpp>
+#include <boost/format.hpp>
+#include "base/Marcos.h"
+#include "Python/PythonEntry.h"
+
+namespace Egametang {
+
+PythonEntry::PythonEntry():
+		python_init_()
+{
+	main_ns_ = import("__main__").attr("__dict__");
+}
+
+void PythonEntry::ImportPath(std::string& path)
+{
+	python_paths_.insert(path);
+}
+
+void PythonEntry::ImportModule(std::string& module)
+{
+	python_modules_.insert(module);
+}
+
+template <typename T>
+void PythonEntry::RegisterObjectPtr(std::string& name, T object_ptr)
+{
+	main_ns_[name.c_str()] = object_ptr;
+}
+
+bool PythonEntry::GetExecString(const std::string& main_fun, std::string& exec_string)
+{
+	exec_string = "import sys\n";
+	boost::format format;
+	if (python_paths_.size() == 0)
+	{
+		LOG(WARNNING) << "no python path";
+		return false;
+	}
+	foreach(std::string& path, python_paths_)
+	{
+		exec_string += format("sys.path.append('%1%')\n") % path;
+	}
+
+	if (python_modules_.size() == 0)
+	{
+		LOG(WARNNING) << "no python module";
+		return false;
+	}
+	foreach(std::string& module, python_modules_)
+	{
+		exec_string += format("import %1%\n") % module;
+	}
+	exec_string += main_fun;
+
+	return true;
+}
+
+void PythonEntry::Exec(std::string& main_fun)
+{
+	std::string exec_string;
+	if (!GetExecString(main_fun, exec_string))
+	{
+		return;
+	}
+
+	try
+	{
+		boost::python::exec(exec_string.c_str(), main_ns_);
+	}
+	catch
+	{
+		LOG(ERROR) << "run python exec error";
+		python_init.PrintError();
+	}
+}
+
+} // namespace Egametang

+ 39 - 0
Src/Egametang/Python/PythonEntry.h

@@ -0,0 +1,39 @@
+#ifndef PYTHON_PYTHON_ENTRY_H
+#define PYTHON_PYTHON_ENTRY_H
+
+#include <boost/noncopyable.hpp>
+#include <boost/python.hpp>
+#include "Python/PythonInit.h"
+
+namespace Egametang {
+
+class PythonEntry: private boost::noncopyable
+{
+private:
+	PythonInit python_init_;
+
+	boost::python::object main_ns_;
+
+	boost::unordered_set<std::string> python_paths_;
+
+	boost::unordered_set<std::string> python_modules_;
+
+public:  // private
+	bool PythonEntry::GetExecString(const std::string& main_fun, std::string& exec_string);
+
+public:
+	PythonEntry();
+
+	void ImportPath(std::string& path);
+
+	void ImportModule(std::string& module);
+
+	template <typename T>
+	void RegisterObjectPtr(std::string& name, T object_ptr);
+
+	void Exec();
+};
+
+} // namespace Egametang
+
+#endif // PYTHON_PYTHON_ENTRY_H

+ 0 - 1
Src/Egametang/Python/PythonInitTest.cc

@@ -112,7 +112,6 @@ TEST_F(PythonInitTest, EnterPythonScript)
 		main_namespace["person"] = person;
 		std::string str = "import sys\n"
 				"sys.path.append('../../../Src/Egametang/Python/')\n"
-				"import PersonTest\n"
 				"import PythonInitTest\n"
 				"PythonInitTest.fun(person)\n";
 		ASSERT_EQ(0, person->Guid());