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.
Post Reply
User avatar
uwestoehr
Posts: 1955
Joined: Sun Jan 27, 2019 3:21 am

how to read return values of Python commands

Post by uwestoehr » Sun Oct 25, 2020 4:07 am

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
Posts: 1955
Joined: Sun Jan 27, 2019 3:21 am

Re: how to read return values of Python commands

Post by uwestoehr » Sun Oct 25, 2020 2:01 pm

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
Site Admin
Posts: 16646
Joined: Thu Feb 19, 2009 10:32 am

Re: how to read return values of Python commands

Post by wmayer » Tue Oct 27, 2020 11:14 am

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
Posts: 1955
Joined: Sun Jan 27, 2019 3:21 am

Re: how to read return values of Python commands

Post by uwestoehr » Wed Oct 28, 2020 1:16 am

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

Who is online

Users browsing this forum: No registered users and 5 guests