本文整理汇总了C++中py::Object类的典型用法代码示例。如果您正苦于以下问题:C++ Object类的具体用法?C++ Object怎么用?C++ Object使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Object类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: next
py::Object next ( py::Object self )
{
const py::Object line = readline(self);
if (line.handle() == py::none.handle()) {
return (py::Object());
}
return (line);
}
示例2: x
PythonObject::PythonObject(const Py::Object& object)
: Qross::Object()
, d(new Private(object))
{
#ifdef QROSS_PYTHON_FUNCTION_DEBUG
qrossdebug( QString("PythonObject::PythonObject() constructor") );
#endif
Py::List x( object.dir() );
for(Py::Sequence::iterator i= x.begin(); i != x.end(); ++i) {
std::string s = (*i).str();
if(s == "__init__")
continue;
//if(! m_pyobject.hasAttr( (*i).str() )) continue;
Py::Object o = d->m_pyobject.getAttr(s);
#ifdef QROSS_PYTHON_FUNCTION_DEBUG
QString t;
if(o.isCallable()) t += "isCallable ";
if(o.isDict()) t += "isDict ";
if(o.isList()) t += "isList ";
if(o.isMapping()) t += "isMapping ";
if(o.isNumeric()) t += "isNumeric ";
if(o.isSequence()) t += "isSequence ";
if(o.isTrue()) t += "isTrue ";
if(o.isInstance()) t += "isInstance ";
qrossdebug( QString("PythonObject::PythonObject() method '%1' (%2)").arg( (*i).str().as_string().c_str() ).arg(t) );
#endif
if(o.isCallable())
d->m_calls.append( (*i).str().as_string().c_str() );
}
}
示例3: module
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
Base::PyGILStateLocker lock;
QMap<QString, CallTip> tips;
if (context.isEmpty())
return tips;
try {
QStringList items = context.split(QLatin1Char('.'));
Py::Module module("__main__");
Py::Dict dict = module.getDict();
QString modname = items.front();
items.pop_front();
if (!dict.hasKey(std::string(modname.toAscii())))
return tips; // unknown object
// get the Python object we need
Py::Object obj = dict.getItem(std::string(modname.toAscii()));
while (!items.isEmpty()) {
QByteArray name = items.front().toAscii();
std::string attr = name.constData();
items.pop_front();
if (obj.hasAttr(attr))
obj = obj.getAttr(attr);
else
return tips;
}
// Checks whether the type is a subclass of PyObjectBase because to get the doc string
// of a member we must get it by its type instead of its instance otherwise we get the
// wrong string, namely that of the type of the member.
// Note: 3rd party libraries may use their own type object classes so that we cannot
// reliably use Py::Type. To be on the safe side we should use Py::Object to assign
// the used type object to.
//Py::Object type = obj.type();
Py::Object type(PyObject_Type(obj.ptr()), true);
Py::Object inst = obj; // the object instance
union PyType_Object typeobj = {&Base::PyObjectBase::Type};
union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
// From the template Python object we don't query its type object because there we keep
// a list of additional methods that we won't see otherwise. But to get the correct doc
// strings we query the type's dict in the class itself.
// To see if we have a template Python object we check for the existence of supportedProperties
if (!type.hasAttr("supportedProperties")) {
obj = type;
}
}
else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
obj = type;
}
// If we have an instance of PyObjectBase then determine whether it's valid or not
if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
}
else {
// PyObject_IsInstance might set an exception
PyErr_Clear();
}
Py::List list(PyObject_Dir(obj.ptr()), true);
// If we derive from PropertyContainerPy we can search for the properties in the
// C++ twin class.
union PyType_Object proptypeobj = {&App::PropertyContainerPy::Type};
if (PyObject_IsSubclass(type.ptr(), proptypeobj.o) == 1) {
// These are the attributes of the instance itself which are NOT accessible by
// its type object
extractTipsFromProperties(inst, tips);
}
// If we derive from App::DocumentPy we have direct access to the objects by their internal
// names. So, we add these names to the list, too.
union PyType_Object appdoctypeobj = {&App::DocumentPy::Type};
if (PyObject_IsSubclass(type.ptr(), appdoctypeobj.o) == 1) {
App::DocumentPy* docpy = (App::DocumentPy*)(inst.ptr());
App::Document* document = docpy->getDocumentPtr();
// Make sure that the C++ object is alive
if (document) {
std::vector<App::DocumentObject*> objects = document->getObjects();
Py::List list;
for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
list.append(Py::String((*it)->getNameInDocument()));
extractTipsFromObject(inst, list, tips);
}
}
// If we derive from Gui::DocumentPy we have direct access to the objects by their internal
// names. So, we add these names to the list, too.
union PyType_Object guidoctypeobj = {&Gui::DocumentPy::Type};
if (PyObject_IsSubclass(type.ptr(), guidoctypeobj.o) == 1) {
Gui::DocumentPy* docpy = (Gui::DocumentPy*)(inst.ptr());
if (docpy->getDocumentPtr()) {
App::Document* document = docpy->getDocumentPtr()->getDocument();
// Make sure that the C++ object is alive
if (document) {
std::vector<App::DocumentObject*> objects = document->getObjects();
Py::List list;
//.........这里部分代码省略.........
示例4: name
TaskWatcherPython::TaskWatcherPython(const Py::Object& o)
: TaskWatcher(0), watcher(o)
{
QString title;
if (watcher.hasAttr(std::string("title"))) {
Py::String name(watcher.getAttr(std::string("title")));
std::string s = (std::string)name;
title = QString::fromUtf8(s.c_str());
}
QPixmap icon;
if (watcher.hasAttr(std::string("icon"))) {
Py::String name(watcher.getAttr(std::string("icon")));
std::string s = (std::string)name;
icon = BitmapFactory().pixmap(s.c_str());
}
Gui::TaskView::TaskBox *tb = 0;
if (watcher.hasAttr(std::string("commands"))) {
if (!tb) tb = new Gui::TaskView::TaskBox(icon, title, true, 0);
Py::List cmds(watcher.getAttr(std::string("commands")));
CommandManager &mgr = Gui::Application::Instance->commandManager();
for (Py::List::iterator it = cmds.begin(); it != cmds.end(); ++it) {
Py::String name(*it);
std::string s = (std::string)name;
Command *c = mgr.getCommandByName(s.c_str());
if (c)
c->addTo(tb);
}
}
if (watcher.hasAttr(std::string("widgets"))) {
if (!tb && !title.isEmpty())
tb = new Gui::TaskView::TaskBox(icon, title, true, 0);
Py::List list(watcher.getAttr(std::string("widgets")));
Py::Module mainmod(PyImport_AddModule((char*)"sip"));
Py::Callable func = mainmod.getDict().getItem("unwrapinstance");
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
Py::Tuple arguments(1);
arguments[0] = *it; //PyQt pointer
Py::Object result = func.apply(arguments);
void* ptr = PyLong_AsVoidPtr(result.ptr());
QObject* object = reinterpret_cast<QObject*>(ptr);
if (object) {
QWidget* w = qobject_cast<QWidget*>(object);
if (w) {
if (tb)
tb->groupLayout()->addWidget(w);
else
Content.push_back(w);
}
}
}
}
if (tb) Content.push_back(tb);
if (watcher.hasAttr(std::string("filter"))) {
Py::String name(watcher.getAttr(std::string("filter")));
std::string s = (std::string)name;
this->setFilter(s.c_str());
}
}
示例5: sysmod
PythonInterpreter::PythonInterpreter(Kross::InterpreterInfo* info)
: Kross::Interpreter(info)
, d(new PythonInterpreterPrivate())
{
// Initialize the python interpreter.
initialize();
// Set name of the program.
Py_SetProgramName(const_cast<char*>("Kross"));
/*
// Set arguments.
//char* comm[0];
const char* comm = const_cast<char*>("kross"); // name.
PySys_SetArgv(1, comm);
*/
// In the python sys.path are all module-directories are
// listed in.
QString path;
// First import the sys-module to remember it's sys.path
// list in our path QString.
Py::Module sysmod( PyImport_ImportModule( (char*)"sys" ), true );
Py::Dict sysmoddict = sysmod.getDict();
Py::Object syspath = sysmoddict.getItem("path");
if(syspath.isList()) {
Py::List syspathlist = syspath;
for(Py::List::iterator it = syspathlist.begin(); it != syspathlist.end(); ++it) {
if( ! (*it).isString() ) continue;
QString s = PythonType<QString>::toVariant(*it);
path.append( s + PYPATHDELIMITER );
}
}
else
path = Py_GetPath();
#if 0
// Determinate additional module-paths we like to add.
// First add the global Kross modules-path.
QStringList krossdirs = KGlobal::dirs()->findDirs("data", "kross/python");
for(QStringList::Iterator krossit = krossdirs.begin(); krossit != krossdirs.end(); ++krossit)
path.append(*krossit + PYPATHDELIMITER);
// Then add the application modules-path.
QStringList appdirs = KGlobal::dirs()->findDirs("appdata", "kross/python");
for(QStringList::Iterator appit = appdirs.begin(); appit != appdirs.end(); ++appit)
path.append(*appit + PYPATHDELIMITER);
#endif
// Set the extended sys.path.
PySys_SetPath( (char*) path.toLatin1().data() );
#ifdef KROSS_PYTHON_INTERPRETER_DEBUG
krossdebug(QString("Python ProgramName: %1").arg(Py_GetProgramName()));
krossdebug(QString("Python ProgramFullPath: %1").arg(Py_GetProgramFullPath()));
krossdebug(QString("Python Version: %1").arg(Py_GetVersion()));
krossdebug(QString("Python Platform: %1").arg(Py_GetPlatform()));
krossdebug(QString("Python Prefix: %1").arg(Py_GetPrefix()));
krossdebug(QString("Python ExecPrefix: %1").arg(Py_GetExecPrefix()));
//krossdebug(QString("Python Path: %1").arg(Py_GetPath()));
//krossdebug(QString("Python System Path: %1").arg(path));
#endif
// Initialize the main module.
d->mainmodule = new PythonModule(this);
// The main dictonary.
Py::Dict moduledict = d->mainmodule->getDict();
//TODO moduledict["KrossPythonVersion"] = Py::Int(KROSS_PYTHON_VERSION);
// Prepare the interpreter.
QString s =
//"# -*- coding: iso-8859-1 -*-\n"
//"import locale\n"
//"locale.setlocale(locale.LC_ALL, '')\n"
//"# -*- coding: latin-1 -*\n"
//"# -*- coding: utf-8 -*-\n"
//"import locale\n"
//"locale.setlocale(locale.LC_ALL, '')\n"
//"from __future__ import absolute_import\n"
"import sys\n"
//"import os, os.path\n"
//"sys.setdefaultencoding('latin-1')\n"
// Dirty hack to get sys.argv defined. Needed for e.g. TKinter.
"sys.argv = ['']\n"
// On the try to read something from stdin always return an empty
// string. That way such reads don't block our script.
// Deactivated since sys.stdin has the encoding attribute needed
// by e.g. LiquidWeather and those attr is missing in StringIO
// and cause it's buildin we can't just add it but would need to
// implement our own class. Grrrr, what a stupid design :-/
//"try:\n"
//" import cStringIO\n"
//" sys.stdin = cStringIO.StringIO()\n"
//"except:\n"
//" pass\n"
// Class to redirect something. We use this class e.g. to redirect
//.........这里部分代码省略.........
示例6: module
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
Base::PyGILStateLocker lock;
QMap<QString, CallTip> tips;
if (context.isEmpty())
return tips;
try {
Py::Module module("__main__");
Py::Dict dict = module.getDict();
#if 0
QStringList items = context.split(QLatin1Char('.'));
QString modname = items.front();
items.pop_front();
if (!dict.hasKey(std::string(modname.toLatin1())))
return tips; // unknown object
// get the Python object we need
Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
while (!items.isEmpty()) {
QByteArray name = items.front().toLatin1();
std::string attr = name.constData();
items.pop_front();
if (obj.hasAttr(attr))
obj = obj.getAttr(attr);
else
return tips;
}
#else
// Don't use hasattr & getattr because if a property is bound to a method this will be executed twice.
PyObject* code = Py_CompileString(static_cast<const char*>(context.toLatin1()), "<CallTipsList>", Py_eval_input);
if (!code) {
PyErr_Clear();
return tips;
}
PyObject* eval = 0;
if (PyCode_Check(code)) {
eval = PyEval_EvalCode(reinterpret_cast<PyCodeObject*>(code), dict.ptr(), dict.ptr());
}
Py_DECREF(code);
if (!eval) {
PyErr_Clear();
return tips;
}
Py::Object obj(eval, true);
#endif
// Checks whether the type is a subclass of PyObjectBase because to get the doc string
// of a member we must get it by its type instead of its instance otherwise we get the
// wrong string, namely that of the type of the member.
// Note: 3rd party libraries may use their own type object classes so that we cannot
// reliably use Py::Type. To be on the safe side we should use Py::Object to assign
// the used type object to.
//Py::Object type = obj.type();
Py::Object type(PyObject_Type(obj.ptr()), true);
Py::Object inst = obj; // the object instance
union PyType_Object typeobj = {&Base::PyObjectBase::Type};
union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
union PyType_Object basetype = {&PyBaseObject_Type};
if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
// From the template Python object we don't query its type object because there we keep
// a list of additional methods that we won't see otherwise. But to get the correct doc
// strings we query the type's dict in the class itself.
// To see if we have a template Python object we check for the existence of supportedProperties
if (!type.hasAttr("supportedProperties")) {
obj = type;
}
}
else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
obj = type;
}
else if (PyInstance_Check(obj.ptr())) {
// instances of old style classes
PyInstanceObject* inst = reinterpret_cast<PyInstanceObject*>(obj.ptr());
PyObject* classobj = reinterpret_cast<PyObject*>(inst->in_class);
obj = Py::Object(classobj);
}
else if (PyObject_IsInstance(obj.ptr(), basetype.o) == 1) {
// New style class which can be a module, type, list, tuple, int, float, ...
// Make sure it's not a type objec
union PyType_Object typetype = {&PyType_Type};
if (PyObject_IsInstance(obj.ptr(), typetype.o) != 1) {
// this should be now a user-defined Python class
// http://stackoverflow.com/questions/12233103/in-python-at-runtime-determine-if-an-object-is-a-class-old-and-new-type-instan
if (Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) {
obj = type;
}
}
}
// If we have an instance of PyObjectBase then determine whether it's valid or not
if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
}
else {
// PyObject_IsInstance might set an exception
PyErr_Clear();
//.........这里部分代码省略.........
示例7: extractTipsFromObject
void CallTipsList::extractTipsFromObject(Py::Object& obj, Py::List& list, QMap<QString, CallTip>& tips) const
{
try {
for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
Py::String attrname(*it);
Py::Object attr = obj.getAttr(attrname.as_string());
CallTip tip;
QString str = QString::fromLatin1(attrname.as_string().c_str());
tip.name = str;
if (attr.isCallable()) {
union PyType_Object basetype = {&PyBaseObject_Type};
if (PyObject_IsSubclass(attr.ptr(), basetype.o) == 1) {
tip.type = CallTip::Class;
}
else {
PyErr_Clear(); // PyObject_IsSubclass might set an exception
tip.type = CallTip::Method;
}
}
else if (PyModule_Check(attr.ptr())) {
tip.type = CallTip::Module;
}
else {
tip.type = CallTip::Member;
}
if (str == QLatin1String("__doc__") && attr.isString()) {
Py::Object help = attr;
if (help.isString()) {
Py::String doc(help);
QString longdoc = QString::fromUtf8(doc.as_string().c_str());
int pos = longdoc.indexOf(QLatin1Char('\n'));
pos = qMin(pos, 70);
if (pos < 0)
pos = qMin(longdoc.length(), 70);
tip.description = stripWhiteSpace(longdoc);
tip.parameter = longdoc.left(pos);
}
}
else if (attr.hasAttr("__doc__")) {
Py::Object help = attr.getAttr("__doc__");
if (help.isString()) {
Py::String doc(help);
QString longdoc = QString::fromUtf8(doc.as_string().c_str());
int pos = longdoc.indexOf(QLatin1Char('\n'));
pos = qMin(pos, 70);
if (pos < 0)
pos = qMin(longdoc.length(), 70);
tip.description = stripWhiteSpace(longdoc);
tip.parameter = longdoc.left(pos);
}
}
tips[str] = tip;
}
}
catch (Py::Exception& e) {
// Just clear the Python exception
e.clear();
}
}