Extra python modules/ru: Difference between revisions

From FreeCAD Documentation
(Updating to match new version of source page)
(Updating to match new version of source page)
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
<languages/>
<languages/>
{{docnav|Localisation|Source documentation}}


{{Docnav
|[[Module_Creation|Module Creation]]
|[[Source_documentation|Source documentation]]
}}

{{TOCright}}

==Overview==
This page lists several additional python modules or other pieces of software that can be downloaded freely from the internet, and add functionality to your FreeCAD installation.
This page lists several additional python modules or other pieces of software that can be downloaded freely from the internet, and add functionality to your FreeCAD installation.


Line 22: Line 29:


==== MacOSX ====
==== MacOSX ====
PyQt on Mac can be installed via homebrew or port. See [[Compile on MacOS#Install_Dependencies]] for more information.
PyQt on Mac can be installed via homebrew or port. See [[Compile on MacOS#Install_Dependencies|Install dependencies]] for more information.


=== Usage ===
=== Usage ===
Once it is installed, you can check that everything is working by typing in FreeCAD python console:
Once it is installed, you can check that everything is working by typing in FreeCAD python console:

{{Code|code=
{{Code|code=
import PySide
import PySide
}}
}}

To access the FreeCAD interface, type :
To access the FreeCAD interface, type :

{{Code|code=
{{Code|code=
from PySide import QtCore,QtGui
from PySide import QtCore,QtGui
FreeCADWindow = FreeCADGui.getMainWindow()
FreeCADWindow = FreeCADGui.getMainWindow()
}}
}}

Now you can start to explore the interface with the dir() command. You can add new elements, like a custom widget, with commands like :
Now you can start to explore the interface with the dir() command. You can add new elements, like a custom widget, with commands like :

{{Code|code=
{{Code|code=
FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)
FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)
}}
}}

Working with Unicode :
Working with Unicode :

{{Code|code=
{{Code|code=
text = text.encode('utf-8')
text = text.encode('utf-8')
}}
}}

Working with QFileDialog and OpenFileName :
Working with QFileDialog and OpenFileName :

{{Code|code=
{{Code|code=
path = FreeCAD.ConfigGet("AppHomePath")
path = FreeCAD.ConfigGet("AppHomePath")
Line 48: Line 64:
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt")
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt")
}}
}}

Working with QFileDialog and SaveFileName :
Working with QFileDialog and SaveFileName :

{{Code|code=
{{Code|code=
path = FreeCAD.ConfigGet("AppHomePath")
path = FreeCAD.ConfigGet("AppHomePath")
Line 54: Line 72:
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")
}}
}}

===Example of transition from PyQt4 and PySide===
===Example of transition from PyQt4 and PySide===


PS: these examples of errors were found in the transition from PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above
PS: these examples of errors were found in the transition from PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above

{{Code|code=
{{Code|code=
try:
try:
Line 75: Line 95:
from PySide.QtCore import * # PySide
from PySide.QtCore import * # PySide
}}
}}

To access the FreeCAD interface, type :
To access the FreeCAD interface, type :
You can add new elements, like a custom widget, with commands like :
You can add new elements, like a custom widget, with commands like :

{{Code|code=
{{Code|code=
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dockwidget
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dockwidget
Line 89: Line 111:
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
}}
}}

Working with Unicode :
Working with Unicode :

{{Code|code=
{{Code|code=
try:
try:
Line 96: Line 120:
text = text.encode('utf-8') # PySide
text = text.encode('utf-8') # PySide
}}
}}

Working with QFileDialog and OpenFileName :
Working with QFileDialog and OpenFileName :

{{Code|code=
{{Code|code=
OpenName = ""
OpenName = ""
Line 104: Line 130:
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide
}}
}}

Working with QFileDialog and SaveFileName :
Working with QFileDialog and SaveFileName :

{{Code|code=
{{Code|code=
SaveName = ""
SaveName = ""
Line 112: Line 140:
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide
}}
}}

The MessageBox:
The MessageBox:

{{Code|code=
{{Code|code=
def errorDialog(msg):
def errorDialog(msg):
Line 123: Line 153:
diag.exec_()
diag.exec_()
}}
}}

Working with setProperty (PyQt4) and setValue (PySide)
Working with setProperty (PyQt4) and setValue (PySide)

{{Code|code=
{{Code|code=
self.doubleSpinBox.setProperty("value", 10.0) # PyQt4
self.doubleSpinBox.setProperty("value", 10.0) # PyQt4
}}
}}

replace with :
replace with :

{{Code|code=
{{Code|code=
self.doubleSpinBox.setValue(10.0) # PySide
self.doubleSpinBox.setValue(10.0) # PySide
}}
}}

Working with setToolTip
Working with setToolTip

{{Code|code=
{{Code|code=
self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None)) # PyQt4
self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None)) # PyQt4
}}
}}

replace with :
replace with :

{{Code|code=
{{Code|code=
self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y")) # PySide
self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y")) # PySide
}}
}}

or :
or :

{{Code|code=
{{Code|code=
self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide
self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide
Line 179: Line 219:
Лучший способ скомпилировать pivy просто вытянуть debian пакет с исходными кодами для pivy и сделать пакет с помощью debuild. Это тот же исходный код что и на оффициальном сайте pivy , но люди debian исправили несколько ошибок. Он также хорошо компилируется в ubuntu karmic из: http://packages.debian.org/squeeze/python-pivy (скачайте .orig.gz и .diff.gz файл, распокуйте оба, добавте .diff к исходному коду: перейдите к каталогу с распакованными кодами pivy , и примените .diff патч:
Лучший способ скомпилировать pivy просто вытянуть debian пакет с исходными кодами для pivy и сделать пакет с помощью debuild. Это тот же исходный код что и на оффициальном сайте pivy , но люди debian исправили несколько ошибок. Он также хорошо компилируется в ubuntu karmic из: http://packages.debian.org/squeeze/python-pivy (скачайте .orig.gz и .diff.gz файл, распокуйте оба, добавте .diff к исходному коду: перейдите к каталогу с распакованными кодами pivy , и примените .diff патч:
</div>
</div>

{{Code|code=
{{Code|code=
patch -p1 < ../pivy_0.5.0~svn765-2.diff
patch -p1 < ../pivy_0.5.0~svn765-2.diff
}}
}}

затем
затем

{{Code|code=
{{Code|code=
debuild
debuild
}}
}}

теперь у вас есть правильно собраный pivy в оффициально устанавливаемых пакетах. Теперь, просто установите пакет с помощью gdebi.
теперь у вас есть правильно собраный pivy в оффициально устанавливаемых пакетах. Теперь, просто установите пакет с помощью gdebi.


Line 191: Line 235:


Сперва получите код из официального репозитория проекта:
Сперва получите код из официального репозитория проекта:

{{Code|code=
{{Code|code=
hg clone http://hg.sim.no/Pivy/default Pivy
hg clone http://hg.sim.no/Pivy/default Pivy
}}
}}

As of March 2012, the latest version is Pivy-0.5.
As of March 2012, the latest version is Pivy-0.5.


Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз [http://www.swig.org http://www.swig.org]. Распакуйте и в командной строке (под root-ом):
Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз [http://www.swig.org http://www.swig.org]. Распакуйте и в командной строке (под root-ом):

{{Code|code=
{{Code|code=
./configure
./configure
Line 202: Line 249:
make install (or checkinstall if you use it)
make install (or checkinstall if you use it)
}}
}}

Сборка занимает всего несколько секунд.
Сборка занимает всего несколько секунд.


Line 207: Line 255:


After that go to the pivy sources and call
After that go to the pivy sources and call

{{Code|code=
{{Code|code=
python setup.py build
python setup.py build
}}
}}

which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.
which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.


Line 215: Line 265:


After that, install by issuing (as root):
After that, install by issuing (as root):

{{Code|code=
{{Code|code=
python setup.py install (or checkinstall python setup.py install)
python setup.py install (or checkinstall python setup.py install)
}}
}}

That's it, pivy is installed.
That's it, pivy is installed.


Line 224: Line 276:


As for linux, get the latest source:
As for linux, get the latest source:

{{Code|code=
{{Code|code=
hg clone http://hg.sim.no/Pivy/default Pivy
hg clone http://hg.sim.no/Pivy/default Pivy
}}
}}

If you don't have hg, you can get it from MacPorts:
If you don't have hg, you can get it from MacPorts:

{{Code|code=
{{Code|code=
port install mercurial
port install mercurial
}}
}}

Then, as above you need SWIG. It should be a matter of:
Then, as above you need SWIG. It should be a matter of:

{{Code|code=
{{Code|code=
port install swig
port install swig
}}
}}

I found I needed also:
I found I needed also:

{{Code|code=
{{Code|code=
port install swig-python
port install swig-python
}}
}}

As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest: https://sourceforge.net/mailarchive/message.php?msg_id=28114815
As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest: https://sourceforge.net/mailarchive/message.php?msg_id=28114815


This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:
This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:

{{Code|code=
{{Code|code=
python setup.py build
python setup.py build
sudo python setup.py install
sudo python setup.py install
}}
}}

====Windows====
====Windows====


Предполагается использование Visual Studio 2005 или позднии версии вы предется открыть командную строку 'Visual Studio 2005 Command prompt' из меню Tools.
Предполагается использование Visual Studio 2005 или позднии версии вы предется открыть командную строку 'Visual Studio 2005 Command prompt' из меню Tools.
Если Python интерпритатор ещё не прописан в системном пути, сделайте это
Если Python интерпритатор ещё не прописан в системном пути, сделайте это

{{Code|code=
{{Code|code=
set PATH=path_to_python_2.5;%PATH%
set PATH=path_to_python_2.5;%PATH%
}}
}}

Чтобы получить работающий pivy вы должны получить последнюю версию исходников из репозитория проекта:
Чтобы получить работающий pivy вы должны получить последнюю версию исходников из репозитория проекта:

{{Code|code=
{{Code|code=
svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy
svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy
}}
}}

Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз [http://www.swig.org http://www.swig.org]. Затем распакуйте его и в командной строке добавте к системному пути
Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз [http://www.swig.org http://www.swig.org]. Затем распакуйте его и в командной строке добавте к системному пути

{{Code|code=
{{Code|code=
set PATH=path_to_swig_1.3.25;%PATH%
set PATH=path_to_swig_1.3.25;%PATH%
}}
}}

и установите COINDIR на соответсвующий путь
и установите COINDIR на соответсвующий путь

{{Code|code=
{{Code|code=
set COINDIR=path_to_coin
set COINDIR=path_to_coin
}}
}}

В Windows pivy конфигурационный файл нахотится в SoWin вместо SoQt по умолчанию. Мне не удалось найти очевидный способ собрать с SoQt, поэтому я изменил файл непосредственно setup.py.
В Windows pivy конфигурационный файл нахотится в SoWin вместо SoQt по умолчанию. Мне не удалось найти очевидный способ собрать с SoQt, поэтому я изменил файл непосредственно setup.py.
В 200 строке удалите часть 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (не удалйте закрывающиеся скобки).
В 200 строке удалите часть 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (не удалйте закрывающиеся скобки).


После чего отправляйтесь к исходным кодам pivy и введите команду
После чего отправляйтесь к исходным кодам pivy и введите команду

{{Code|code=
{{Code|code=
python setup.py build
python setup.py build
}}
}}

которая создаст исходные файлы. Вы можете столкнуться с ошибками компилятора -несколько заголовочных файлов не может быть найдено. В этом случае отрегулируйте INCLUDE переменную
которая создаст исходные файлы. Вы можете столкнуться с ошибками компилятора -несколько заголовочных файлов не может быть найдено. В этом случае отрегулируйте INCLUDE переменную

{{Code|code=
{{Code|code=
set INCLUDE=%INCLUDE%;path_to_coin_include_dir
set INCLUDE=%INCLUDE%;path_to_coin_include_dir
}}
}}

если нет заголовочных файлов SoQt на месте , также с заголовками Coin
если нет заголовочных файлов SoQt на месте , также с заголовками Coin

{{Code|code=
{{Code|code=
set INCLUDE=%INCLUDE%;path_to_soqt_include_dir
set INCLUDE=%INCLUDE%;path_to_soqt_include_dir
}}
}}

и в конце Qt заголовочные файлы
и в конце Qt заголовочные файлы

{{Code|code=
{{Code|code=
set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt
set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt
}}
}}

Если вы используете Express Edition версию Visual Studio вы можете получить исключение python keyerror.
Если вы используете Express Edition версию Visual Studio вы можете получить исключение python keyerror.
В этом случае Вам необходимо изменить кое-что в msvccompiler.py расположенный в месте кужа вы установили Python.
В этом случае Вам необходимо изменить кое-что в msvccompiler.py расположенный в месте кужа вы установили Python.


шагом марш на 122 строку и замените строку
шагом марш на 122 строку и замените строку

{{Code|code=
{{Code|code=
vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
}}
}}

на
на

{{Code|code=
{{Code|code=
vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version
vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version
}}
}}

Повторите сборку снова.
Повторите сборку снова.
Если вы получили вторую ошибку, вроде
Если вы получили вторую ошибку, вроде

{{Code|code=
{{Code|code=
error: Python was built with Visual Studio 2003;...
error: Python was built with Visual Studio 2003;...
}}
}}

вы должны поменять 128 строку
вы должны поменять 128 строку

{{Code|code=
{{Code|code=
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
}}
}}

на
на

{{Code|code=
{{Code|code=
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")
}}
}}

Повторите сборку снова. Если вы опять получили ошибку
Повторите сборку снова. Если вы опять получили ошибку

{{Code|code=
{{Code|code=
error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed.
error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed.
}}
}}

проверте пересеменные окружения DISTUTILS_USE_SDK и MSSDK с помощью
проверте пересеменные окружения DISTUTILS_USE_SDK и MSSDK с помощью

{{Code|code=
{{Code|code=
echo %DISTUTILS_USE_SDK%
echo %DISTUTILS_USE_SDK%
echo %MSSDK%
echo %MSSDK%
}}
}}

Если они еще не установлены, то просто установите например, до 1
Если они еще не установлены, то просто установите например, до 1

{{Code|code=
{{Code|code=
set DISTUTILS_USE_SDK=1
set DISTUTILS_USE_SDK=1
set MSSDK=1
set MSSDK=1
}}
}}

Вы можете столкнуться при компиляции с ошибкой 'const char*' cannot be converted in a 'char*'. Чтобы исправить это вам необходимо написать 'const' перед следующей строкой(char*). Исправте ещё шесть строк.
Вы можете столкнуться при компиляции с ошибкой 'const char*' cannot be converted in a 'char*'. Чтобы исправить это вам необходимо написать 'const' перед следующей строкой(char*). Исправте ещё шесть строк.
После чего, скопируйте созданный pivy каталог, в место где python интрепритатор FreeCAD сможет найти его.
После чего, скопируйте созданный pivy каталог, в место где python интрепритатор FreeCAD сможет найти его.
Line 328: Line 422:
=== Usage ===
=== Usage ===
To check if Pivy is correctly installed:
To check if Pivy is correctly installed:

{{Code|code=
{{Code|code=
import pivy
import pivy
}}
}}

Чтобы Pivy получил доступ FreeCAD древу сцен сделайте следующие:
Чтобы Pivy получил доступ FreeCAD древу сцен сделайте следующие:

{{Code|code=
{{Code|code=
from pivy import coin
from pivy import coin
Line 339: Line 436:
FCSceneGraph.addChild(coin.SoCube()) # add a box to scene
FCSceneGraph.addChild(coin.SoCube()) # add a box to scene
}}
}}

Теперь вы можете изучать FCSceneGraph с помощью команды dir().
Теперь вы можете изучать FCSceneGraph с помощью команды dir().


Line 361: Line 459:
==== Linux ====
==== Linux ====
In either case, you'll need the following packages already installed on your system:
In either case, you'll need the following packages already installed on your system:

{{Code|code=
{{Code|code=
python-lxml
python-lxml
Line 366: Line 465:
python-dateutil
python-dateutil
}}
}}

===== From the git repository =====
===== From the git repository =====

{{Code|code=
{{Code|code=
git clone git://github.com/pycollada/pycollada.git pycollada
git clone git://github.com/pycollada/pycollada.git pycollada
Line 372: Line 473:
sudo python setup.py install
sudo python setup.py install
}}
}}

===== With easy_install =====
===== With easy_install =====
Assuming you have a complete python installation already, the easy_install utility should be present already:
Assuming you have a complete python installation already, the easy_install utility should be present already:

{{Code|code=
{{Code|code=
easy_install pycollada
easy_install pycollada
}}
}}

You can check if pycollada was correctly installed by issuing in a python console:
You can check if pycollada was correctly installed by issuing in a python console:

{{Code|code=
{{Code|code=
import collada
import collada
}}
}}

If it returns nothing (no error message), then all is OK
If it returns nothing (no error message), then all is OK


Line 392: Line 498:


If you need to install pip:
If you need to install pip:

{{Code|code=
{{Code|code=
$ sudo easy_install pip
$ sudo easy_install pip
}}
}}

Install pycollada:
Install pycollada:

{{Code|code=
{{Code|code=
$ sudo pip install pycollada
$ sudo pip install pycollada
}}
}}

If you are using a binary version of FreeCAD, you can tell pip to install pycollada into the site-packages inside FreeCAD.app:
If you are using a binary version of FreeCAD, you can tell pip to install pycollada into the site-packages inside FreeCAD.app:

{{Code|code=
{{Code|code=
$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada
$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada
}}
}}

or after downloading the pycollada code
or after downloading the pycollada code

{{Code|code=
{{Code|code=
$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
Line 422: Line 535:
==== Linux ====
==== Linux ====
You will need a couple of development packages installed on your system in order to compile ifcopenshell:
You will need a couple of development packages installed on your system in order to compile ifcopenshell:

{{Code|code=
{{Code|code=
liboce-*-dev
liboce-*-dev
Line 427: Line 541:
swig
swig
}}
}}

but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.
but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.


Grab the latest source code from here:
Grab the latest source code from here:

{{Code|code=
{{Code|code=
git clone https://github.com/IfcOpenShell/IfcOpenShell.git
git clone https://github.com/IfcOpenShell/IfcOpenShell.git
}}
}}

The build process is very easy:
The build process is very easy:

{{Code|code=
{{Code|code=
mkdir ifcopenshell-build
mkdir ifcopenshell-build
Line 439: Line 557:
cmake ../IfcOpenShell/cmake
cmake ../IfcOpenShell/cmake
}}
}}

or, if you are using oce instead of opencascade:
or, if you are using oce instead of opencascade:

{{Code|code=
{{Code|code=
cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake
cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake
}}
}}

Since ifcopenshell is made primarily for Blender, it uses python3 by default. To use it inside FreeCAD, you need to compile it against the same version of python that is used by FreeCAD. So you might need to force the python version with additional cmake parameters (adjust the python version to yours):
Since ifcopenshell is made primarily for Blender, it uses python3 by default. To use it inside FreeCAD, you need to compile it against the same version of python that is used by FreeCAD. So you might need to force the python version with additional cmake parameters (adjust the python version to yours):

{{Code|code=
{{Code|code=
cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake
cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake
}}
}}

Then:
Then:

{{Code|code=
{{Code|code=
make
make
sudo make install
sudo make install
}}
}}

You can check that ifcopenshell was correctly installed by issuing in a python console:
You can check that ifcopenshell was correctly installed by issuing in a python console:

{{Code|code=
{{Code|code=
import ifcopenshell
import ifcopenshell
}}
}}

If it returns nothing (no error message), then all is OK
If it returns nothing (no error message), then all is OK


Line 482: Line 609:
On all platforms, only by installing the appropriate package from https://www.opendesign.com/guestfiles/oda_file_converter . After installation, if the utility is not found automatically by FreeCAD, you might need to set the path to the converter executable manually, open Edit → Preferences → Import-Export → DWG and fill "Path to Teigha File Converter" appropriately.
On all platforms, only by installing the appropriate package from https://www.opendesign.com/guestfiles/oda_file_converter . After installation, if the utility is not found automatically by FreeCAD, you might need to set the path to the converter executable manually, open Edit → Preferences → Import-Export → DWG and fill "Path to Teigha File Converter" appropriately.


== LazyLoader ==
{{docnav/ru|Localisation/ru|Source documentation/ru}}
LazyLoader is a python module that allows deferred loading, while still importing at the top of the script. This is useful if you are importing another module that is slow, and it is used several times throughout the script. Using LazyLoader can improve workbench startup times, but the module will still need to be loaded on first use.


=== Installation ===
{{Userdocnavi}}
LazyLoader is included with FreeCAD v0.19


=== Usage ===
[[Category:Python Code]]
You will need to import LazyLoader, then change the import of whatever module you want to be deferred.


{{Code|code=
[[Category:Developer Documentation/ru]]
from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')
}}
The variable Part is how the module is named in your script. You can replicate "import Part as P" by changing the variable.

{{Code|code=
P = LazyLoader('Part', globals(), 'Part')
}}
You can also import a module from a package.
{{Code|code=
utils = LazyLoader('PathScripts', globals(), 'PathScripts.PathUtils')
}}
You can't import individual functions, just entire modules.

=== Links ===
* Original source: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py
* Further explanation: https://wil.yegelwel.com/lazily-importing-python-modules/
* Code within the FreeCAD source code: https://github.com/FreeCAD/FreeCAD/tree/master/src/3rdParty/lazy_loader
* Forum discussion: https://forum.freecadweb.org/viewtopic.php?f=10&t=45298


<div class="mw-translate-fuzzy">
{{docnav/ru|Localisation/ru|Source documentation/ru}}
</div>


{{Userdocnavi{{#translation:}}}}
[[Category:Python Code{{#translation:}}]]
[[Category:Developer Documentation{{#translation:}}]]
{{clear}}
{{clear}}

Revision as of 15:53, 30 December 2020

Overview

This page lists several additional python modules or other pieces of software that can be downloaded freely from the internet, and add functionality to your FreeCAD installation.

PySide (previously PyQt4)

PySide (previously PyQt) is required by several modules of FreeCAD to access FreeCAD's Qt interface. It is already bundled in the windows verison of FreeCAD, and is usually installed automatically by FreeCAD on Linux, when installing from official repositories. If those modules (Draft, Arch, etc) are enabled after FreeCAD is installed, it means PySide (previously PyQt) is already there, and you don't need to do anything more.

Note: FreeCAD progressively moved away from PyQt after version 0.13, in favour of PySide, which does exactly the same job but has a license (LGPL) more compatible with FreeCAD.

Installation

Linux

The simplest way to install PySide is through your distribution's package manager. On Debian/Ubuntu systems, the package name is generally python-PySide, while on RPM-based systems it is named pyside. The necessary dependencies (Qt and SIP) will be taken care of automatically.

Windows

The program can be downloaded from http://qt-project.org/wiki/Category:LanguageBindings::PySide::Downloads . You'll need to install the Qt and SIP libraries before installing PySide (to be documented).

MacOSX

PyQt on Mac can be installed via homebrew or port. See Install dependencies for more information.

Usage

Once it is installed, you can check that everything is working by typing in FreeCAD python console:

import PySide

To access the FreeCAD interface, type :

from PySide import QtCore,QtGui
FreeCADWindow = FreeCADGui.getMainWindow()

Now you can start to explore the interface with the dir() command. You can add new elements, like a custom widget, with commands like :

FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)

Working with Unicode :

text = text.encode('utf-8')

Working with QFileDialog and OpenFileName :

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt")

Working with QFileDialog and SaveFileName :

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")

Example of transition from PyQt4 and PySide

PS: these examples of errors were found in the transition from PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above

try:
    import PyQt4                                        # PyQt4
    from PyQt4 import QtGui ,QtCore                     # PyQt4
    from PyQt4.QtGui import QComboBox                   # PyQt4
    from PyQt4.QtGui import QMessageBox                 # PyQt4
    from PyQt4.QtGui import QTableWidget, QApplication  # PyQt4
    from PyQt4.QtGui import *                           # PyQt4
    from PyQt4.QtCore import *                          # PyQt4
except Exception:
    import PySide                                       # PySide
    from PySide import QtGui ,QtCore                    # PySide
    from PySide.QtGui import QComboBox                  # PySide
    from PySide.QtGui import QMessageBox                # PySide
    from PySide.QtGui import QTableWidget, QApplication # PySide
    from PySide.QtGui import *                          # PySide
    from PySide.QtCore import *                         # PySide

To access the FreeCAD interface, type : You can add new elements, like a custom widget, with commands like :

myNewFreeCADWidget = QtGui.QDockWidget()          # create a new dockwidget
myNewFreeCADWidget.ui = Ui_MainWindow()           # myWidget_Ui()             # load the Ui script
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
try:
    app = QtGui.qApp                              # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw = app.activeWindow()                     # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
except Exception:
    FCmw = FreeCADGui.getMainWindow()             # PySide # the active qt window, = the freecad window since we are inside it 
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Working with Unicode :

try:
    text = unicode(text, 'ISO-8859-1').encode('UTF-8')  # PyQt4
except Exception:
    text = text.encode('utf-8')                         # PySide

Working with QFileDialog and OpenFileName :

OpenName = ""
try:
    OpenName = QFileDialog.getOpenFileName(None,QString.fromLocal8Bit("Lire un fichier FCInfo ou txt"),path,"*.FCInfo *.txt") # PyQt4
except Exception:
    OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide

Working with QFileDialog and SaveFileName :

SaveName = ""
try:
    SaveName = QFileDialog.getSaveFileName(None,QString.fromLocal8Bit("Sauver un fichier FCInfo"),path,"*.FCInfo") # PyQt4
except Exception:
    SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide

The MessageBox:

def errorDialog(msg):
    diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical,u"Error Message",msg )
    try:
        diag.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint) # PyQt4 # this function sets the window before
    except Exception:    
        diag.setWindowFlags(PySide.QtCore.Qt.WindowStaysOnTopHint)# PySide # this function sets the window before
#    diag.setWindowModality(QtCore.Qt.ApplicationModal)       # function has been disabled to promote "WindowStaysOnTopHint"
    diag.exec_()

Working with setProperty (PyQt4) and setValue (PySide)

self.doubleSpinBox.setProperty("value", 10.0)  # PyQt4

replace with :

self.doubleSpinBox.setValue(10.0)  # PySide

Working with setToolTip

self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None))  # PyQt4

replace with :

self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y"))  # PySide

or :

self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide

Документация

Больше учебников по pyQt4 (в том числе от том как использовать в python интерфейс построенный с помощью Qt Designer):

Pivy

Pivy is a needed by several modules to access the 3D view of FreeCAD. On windows, Pivy is already bundled inside the FreeCAD installer, and on Linux it is usually automatically installed when you install FreeCAD from an official repository. On MacOSX, unfortunately, you will need to compile pivy yourself.

Установка

Prerequisites

I believe before compiling Pivy you will want to have Coin and SoQt installed.

I found for building on Mac it was sufficient to install the Coin3 binary package. Attempting to install coin from MacPorts was problematic: tried to add a lot of X Windows packages and ultimately crashed with a script error.

For Fedora I found an RPM with Coin3.

SoQt compiled from source fine on Mac and Linux.

Debian & Ubuntu

Начиная с Debian Squeeze и Ubuntu Lucid, pivy стал доступен напрямую через официальные репозитории, экономя ваше время. В то же время вы можете скачать один из пакетов что мы сделали (для debian и ubuntu karmic) доступных на странице Загрузок , или скомпилировать их самостоятельно.

Лучший способ скомпилировать pivy просто вытянуть debian пакет с исходными кодами для pivy и сделать пакет с помощью debuild. Это тот же исходный код что и на оффициальном сайте pivy , но люди debian исправили несколько ошибок. Он также хорошо компилируется в ubuntu karmic из: http://packages.debian.org/squeeze/python-pivy (скачайте .orig.gz и .diff.gz файл, распокуйте оба, добавте .diff к исходному коду: перейдите к каталогу с распакованными кодами pivy , и примените .diff патч:

patch -p1 < ../pivy_0.5.0~svn765-2.diff

затем

debuild

теперь у вас есть правильно собраный pivy в оффициально устанавливаемых пакетах. Теперь, просто установите пакет с помощью gdebi.

Другие linux дистрибутивы

Сперва получите код из официального репозитория проекта:

hg clone http://hg.sim.no/Pivy/default Pivy

As of March 2012, the latest version is Pivy-0.5.

Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз http://www.swig.org. Распакуйте и в командной строке (под root-ом):

./configure
make
make install (or checkinstall if you use it)

Сборка занимает всего несколько секунд.

Alternatively, you can try building with a more recent SWIG. As of March 2012, a typical repository version is 2.0.4. Pivy has a minor compile problem with SWIG 2.0.4 on Mac OS (see below) but seems to build fine on Fedora Core 15.

After that go to the pivy sources and call

python setup.py build

which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.

This is probably obsolete, but you may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix.

After that, install by issuing (as root):

python setup.py install (or checkinstall python setup.py install)

That's it, pivy is installed.

Mac OS

These instructions may not be complete. Something close to this worked for OS 10.7 as of March 2012. I use MacPorts for repositories, but other options should also work.

As for linux, get the latest source:

hg clone http://hg.sim.no/Pivy/default Pivy

If you don't have hg, you can get it from MacPorts:

port install mercurial

Then, as above you need SWIG. It should be a matter of:

port install swig

I found I needed also:

port install swig-python

As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest: https://sourceforge.net/mailarchive/message.php?msg_id=28114815

This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:

python setup.py build
sudo python setup.py install

Windows

Предполагается использование Visual Studio 2005 или позднии версии вы предется открыть командную строку 'Visual Studio 2005 Command prompt' из меню Tools. Если Python интерпритатор ещё не прописан в системном пути, сделайте это

set PATH=path_to_python_2.5;%PATH%

Чтобы получить работающий pivy вы должны получить последнюю версию исходников из репозитория проекта:

svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy

Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25 , не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз http://www.swig.org. Затем распакуйте его и в командной строке добавте к системному пути

set PATH=path_to_swig_1.3.25;%PATH%

и установите COINDIR на соответсвующий путь

set COINDIR=path_to_coin

В Windows pivy конфигурационный файл нахотится в SoWin вместо SoQt по умолчанию. Мне не удалось найти очевидный способ собрать с SoQt, поэтому я изменил файл непосредственно setup.py. В 200 строке удалите часть 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (не удалйте закрывающиеся скобки).

После чего отправляйтесь к исходным кодам pivy и введите команду

python setup.py build


которая создаст исходные файлы. Вы можете столкнуться с ошибками компилятора -несколько заголовочных файлов не может быть найдено. В этом случае отрегулируйте INCLUDE переменную

set INCLUDE=%INCLUDE%;path_to_coin_include_dir

если нет заголовочных файлов SoQt на месте , также с заголовками Coin

set INCLUDE=%INCLUDE%;path_to_soqt_include_dir

и в конце Qt заголовочные файлы

set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

Если вы используете Express Edition версию Visual Studio вы можете получить исключение python keyerror. В этом случае Вам необходимо изменить кое-что в msvccompiler.py расположенный в месте кужа вы установили Python.

шагом марш на 122 строку и замените строку

vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version

на

vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version

Повторите сборку снова. Если вы получили вторую ошибку, вроде

error: Python was built with Visual Studio 2003;...

вы должны поменять 128 строку

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")

на

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")

Повторите сборку снова. Если вы опять получили ошибку

error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed.

проверте пересеменные окружения DISTUTILS_USE_SDK и MSSDK с помощью

echo %DISTUTILS_USE_SDK%
echo %MSSDK%

Если они еще не установлены, то просто установите например, до 1

set DISTUTILS_USE_SDK=1
set MSSDK=1

Вы можете столкнуться при компиляции с ошибкой 'const char*' cannot be converted in a 'char*'. Чтобы исправить это вам необходимо написать 'const' перед следующей строкой(char*). Исправте ещё шесть строк. После чего, скопируйте созданный pivy каталог, в место где python интрепритатор FreeCAD сможет найти его.

Usage

To check if Pivy is correctly installed:

import pivy

Чтобы Pivy получил доступ FreeCAD древу сцен сделайте следующие:

from pivy import coin
App.newDocument() # Open a document and a view 
view = Gui.ActiveDocument.ActiveView 
FCSceneGraph = view.getSceneGraph() # returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraph
FCSceneGraph.addChild(coin.SoCube()) # add a box to scene

Теперь вы можете изучать FCSceneGraph с помощью команды dir().

Additonal Documentation

Unfortunately documentation about pivy is still almost nonexistant on the net. But you might find Coin documentation useful, since pivy simply translate Coin functions, nodes and methods in python, everything keeps the same name and properties, keeping in mind the difference of syntax between C and python:

Вы также можете просмотреть в Draft.py файл в папке FreeCAD Mod/Draft , так как там часто используется pivy.

pyCollada

pyCollada is a python library that allow programs to read and write Collada (*.DAE) files. When pyCollada is installed on your system, FreeCAD will be able to handle importing and exporting in the Collada file format.

Installation

Pycollada is usually not yet available in linux distributions repositories, but since it is made only of python files, it doesn't require compilation, and is easy to install. You have 2 ways, or directly from the official pycollada git repository, or with the easy_install tool.

Linux

In either case, you'll need the following packages already installed on your system:

python-lxml 
python-numpy
python-dateutil
From the git repository
git clone git://github.com/pycollada/pycollada.git pycollada
cd pycollada
sudo python setup.py install
With easy_install

Assuming you have a complete python installation already, the easy_install utility should be present already:

easy_install pycollada

You can check if pycollada was correctly installed by issuing in a python console:

import collada

If it returns nothing (no error message), then all is OK

Windows

On Windows since 0.15 pycollada is included in both the FreeCAD release and developer builds so no additional steps are necessary.

Mac OS

If you are using the Homebrew build of FreeCAD you can install pycollada into your system Python using pip.

If you need to install pip:

$ sudo easy_install pip

Install pycollada:

$ sudo pip install pycollada

If you are using a binary version of FreeCAD, you can tell pip to install pycollada into the site-packages inside FreeCAD.app:

$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada

or after downloading the pycollada code

$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
$ python setup.py install --prefix=/Applications/FreeCAD\ 0.16.6706.app/Contents

IfcOpenShell

IFCOpenShell is a library currently in development, that allows to import (and soon export) Industry foundation Classes (*.IFC) files. IFC is an extension to the STEP format, and is becoming the standard in BIM workflows. When ifcopenshell is correctly installed on your system, the FreeCAD Arch Module will detect it and use it to import IFC files, instead of its built-in rudimentary importer. Since ifcopenshell is based on OpenCasCade, like FreeCAD, the quality of the import is very high, producing high-quality solid geometry.

Installation

Since ifcopenshell is pretty new, you'll likely need to compile it yourself.

Linux

You will need a couple of development packages installed on your system in order to compile ifcopenshell:

liboce-*-dev
python-dev
swig

but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.

Grab the latest source code from here:

git clone https://github.com/IfcOpenShell/IfcOpenShell.git

The build process is very easy:

mkdir ifcopenshell-build
cd ifcopenshell-build
cmake ../IfcOpenShell/cmake

or, if you are using oce instead of opencascade:

cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake

Since ifcopenshell is made primarily for Blender, it uses python3 by default. To use it inside FreeCAD, you need to compile it against the same version of python that is used by FreeCAD. So you might need to force the python version with additional cmake parameters (adjust the python version to yours):

cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake

Then:

make
sudo make install

You can check that ifcopenshell was correctly installed by issuing in a python console:

import ifcopenshell

If it returns nothing (no error message), then all is OK

Windows

Note: Official FreeCAD installers obtained from the FreeCAD website/github page now contain ifcopenshell already.

Copied from the IfcOpenShell README file

Users are advised to use the Visual Studio .sln file in the win/ folder. For Windows users a prebuilt Open CASCADE version is available from the http://opencascade.org website. Download and install this version and provide the paths to the Open CASCADE header and library files to MS Visual Studio C++.

For building the IfcPython wrapper, SWIG needs to be installed. Please download the latest swigwin version from http://www.swig.org/download.html . After extracting the .zip file, please add the extracted folder to the PATH environment variable. Python needs to be installed, please provide the include and library paths to Visual Studio.

Links

Tutorial Import/Export IFC - compiling IfcOpenShell

ODA Converter (previously Teigha Converter)

The ODA Converter is a small freely available utility that allows to convert between several versions of DWG and DXF files. FreeCAD can use it to offer DWG import and export, by converting DWG files to the DXF format under the hood,then using its standard DXF importer to import the file contents. The restrictions of the DXF importer apply.

Installation

On all platforms, only by installing the appropriate package from https://www.opendesign.com/guestfiles/oda_file_converter . After installation, if the utility is not found automatically by FreeCAD, you might need to set the path to the converter executable manually, open Edit → Preferences → Import-Export → DWG and fill "Path to Teigha File Converter" appropriately.

LazyLoader

LazyLoader is a python module that allows deferred loading, while still importing at the top of the script. This is useful if you are importing another module that is slow, and it is used several times throughout the script. Using LazyLoader can improve workbench startup times, but the module will still need to be loaded on first use.

Installation

LazyLoader is included with FreeCAD v0.19

Usage

You will need to import LazyLoader, then change the import of whatever module you want to be deferred.

from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')

The variable Part is how the module is named in your script. You can replicate "import Part as P" by changing the variable.

P = LazyLoader('Part', globals(), 'Part')

You can also import a module from a package.

utils = LazyLoader('PathScripts', globals(), 'PathScripts.PathUtils')

You can't import individual functions, just entire modules.

Links


Localisation/ru
Source documentation/ru