how to read return values of Python commands

Here's the place for discussion related to coding in FreeCAD, C++ or Python. Design, interfaces and structures.
Forum rules
Be nice to others! Respect the FreeCAD code of conduct!
Post Reply
User avatar
uwestoehr
Veteran
Posts: 4961
Joined: Sun Jan 27, 2019 3:21 am
Location: Germany
Contact:

how to read return values of Python commands

Post by uwestoehr »

I want to read out properties of a feature using Python. For example I want to read the pitch of a helix. I can execute the right command:

Code: Select all

cmd = QString::fromLatin1(
                "App.ActiveDocument.%1.Pitch\n")
                .arg(ObjectName);
Gui::Command::runCommand(Gui::Command::Doc, cmd);
But how do I get the return value so that I can do something with it in my C++ code?
User avatar
uwestoehr
Veteran
Posts: 4961
Joined: Sun Jan 27, 2019 3:21 am
Location: Germany
Contact:

Re: how to read return values of Python commands

Post by uwestoehr »

I failed to do this but found now a solution how to read out an object property the C++ way. This way I can use the return value directly.
wmayer
Founder
Posts: 20245
Joined: Thu Feb 19, 2009 10:32 am
Contact:

Re: how to read return values of Python commands

Post by wmayer »

In terms of macro recording a line like

Code: Select all

App.ActiveDocument.Helix.Pitch
is pointless anyway because the macro doesn't need it to be executed correctly. So, it's easier to get it via C++ instead.

Things would be different if you assign it to a variable and you want to get its content:

Code: Select all

pitch = App.ActiveDocument.Helix.Pitch
This can be done with:

Code: Select all

Py::Module module("__main__");
Py::Dict dict = module.getDict();

Py::Float pitch(dict.getItem("pitch"));

double value = static_cast<double>(pitch);
User avatar
uwestoehr
Veteran
Posts: 4961
Joined: Sun Jan 27, 2019 3:21 am
Location: Germany
Contact:

Re: how to read return values of Python commands

Post by uwestoehr »

wmayer wrote: Tue Oct 27, 2020 11:14 am This can be done with:
Many thanks. I'll use this for future and as reference.

I came across this while working on making it possible to edit Part's primitives via a dialog.
I found now a C++ solution to get the helix pitch:

Code: Select all

App::Property* Property = docObj->getPropertyByName("Pitch");
App::PropertyQuantity* value = static_cast<const App::PropertyQuantity*>(Property);
and used this in the according PR: https://github.com/FreeCAD/FreeCAD/pull/4000

Besides this, is there a technical reason why there is no function to get a property quantity directly? (to have such a code instead to cast:

Code: Select all

Property->getQuantity()
Post Reply