ViewProvider for (python) objects created in headless mode?

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!
agustavo87
Posts: 10
Joined: Tue Jul 05, 2022 4:17 pm

Re: ViewProvider for (python) objects created in headless mode?

Post by agustavo87 »

wmayer wrote: Wed Feb 24, 2021 6:07 pm

Code: Select all

import FreeCADGui as Gui
from pivy import coin

Gui.setupWithoutGUI()
doc = App.newDocument()
obj = doc.addObject("Part::Box","Box")
doc.recompute()
view = Gui.subgraphFromObject(obj)
Hi, I' trying to run FC to convert some files, when I follow this steps manually headless mode seems to work but when try to load a .py file throws an error. I work on windows and (for example) when run startup.py with the above code

Code: Select all

FreeCADCmd -c startup.py
I get the following error

Code: Select all

Exception while processing file: startup.py [FreeCADGui already initialized]
Although if I just copy and paste on the console works OK. Any idea what I'm missing or how to work it through?
wmayer
Founder
Posts: 20245
Joined: Thu Feb 19, 2009 10:32 am
Contact:

Re: ViewProvider for (python) objects created in headless mode?

Post by wmayer »

agustavo87 wrote: Tue Jul 05, 2022 4:25 pm Although if I just copy and paste on the console works OK. Any idea what I'm missing or how to work it through?
Confirmed.

The call of FreeCADCmd -c startup.py internally tries to import the module like if you wrote import startup. Now this fails because App is not defined.

Because of the failure FreeCAD now tries to execute (see exec vs import) the code and thus calls Gui.setupWithoutGUI() twice which then raises the exception that it's already initialized.

So, to fix it you must add this line at the top

Code: Select all

import FreeCAD as App
An alternative fix would be using the file extension .FCScript or .FCMacro instead of .py because then it internally uses exec immediately.
wmayer
Founder
Posts: 20245
Joined: Thu Feb 19, 2009 10:32 am
Contact:

Re: ViewProvider for (python) objects created in headless mode?

Post by wmayer »

With git commit 212b140d82 I have removed the exception.
agustavo87
Posts: 10
Joined: Tue Jul 05, 2022 4:17 pm

Re: ViewProvider for (python) objects created in headless mode?

Post by agustavo87 »

wmayer wrote: Wed Jul 06, 2022 8:55 am With git commit 212b140d82 I have removed the exception.
Thanks for the fix. Yes I've found that with .FCMacro it worked as intended.
Post Reply