Введение
The Python console is a panel that's part of the FreeCAD user interface. It runs an instance of the Python interpreter which can be used to control FreeCAD processes, and create and modify objects and their properties.
It can be made visible/hidden through the View → Panels → Python console drop-down menu.
The Python console in FreeCAD has basic syntax highlighting, able to differentiate with various styles and colors, comments, strings, numeric values, built in functions, printed text output, and delimiters like parentheses and commas. These properties of the console can be configured in the Preferences editor.
The Python console showing messages when FreeCAD has just started.
Программирование
For absolute beginners, see: Introduction to Python, and Python scripting tutorial.
See also: FreeCAD scripting basics, and Scripted objects.
The Python console can perform basic code completion when a dot is written after an object; it will show public methods and attributes (variables) of the current object (class), for example, obj.
The console is also able to show the documentation string of a particular function when the opening parenthesis is written, for example, function(
Example Python code that produces objects in the 3D view.
The FreeCAD initialization scripts automatically load some modules, and define some aliases. Therefore, in the Python console these are available
App = FreeCAD
Gui = FreeCADGui
Therefore these are equal
App.newDocument()
FreeCAD.newDocument()
Note: these pre-loaded modules and aliases are only available from the Python console embedded inside the FreeCAD program. If you use FreeCAD as a library in an external program, you must remember to load the FreeCAD
and FreeCADGui
modules and define the necessary aliases if you wish.
Действия
Right click on the Python console shows some commands:
- Copy: stores the selected text in the clipboard for later pasting; it is disabled if nothing is selected.
- Copy command: stores the selected command in the clipboard for later pasting; it is disabled if nothing is selected.
- Copy history: copy the entire history of Python commands entered in this session.
- Save history as: save the entire history of Python commands entered in this session to a text file.
- Paste: paste previously copied text in the clipboard to the Python console.
- Select all: selects all text in the Python console.
- Clear console: erases all commands entered into the Python console. This is useful if the Python console is full of messages and previously entered commands that may be distracting when testing a new function. This is merely aesthetic, as this command doesn't delete existing variables nor clears the imported modules in the session.
- Insert file name: opens a dialog to search for a file in the system, then it inserts the full path of the file. This is useful to test functions that process an input file, without having to write the entire name in the console, which is error prone. This command does not run the file, and does not import it as a Python module, it just returns the full path of that file.
- Word wrap: wrap very long lines that exceed the horizontal dimension of the Python console.
Notes
- One has the ability to scroll the API in the Python console. Example:
- In the console type:
FreeCAD.
- A dialog box will display with optional classes/functions to choose from
- Scroll through the list to read the description of each class/function
- By choosing a function and following it with a
.
one can repeat steps 2 and 3 to traverse deeper in to the API
- Tab/Word completion is supported using the Ctrl+Space shortcut
Интерфейс
- Preferences Editor, Interface Customization
- Главное окно: Standard menu, Main view area, 3D view, Combo view (Tree view, Task panel, Property editor), Selection view, Report view, Python console, Status bar, DAG view, Workbench Selector
- Дополнительные окна: Scene inspector, Dependency graph
Std Base
- Файл: Создать, Открыть, Закрыть, Закрыть всё, Сохранить, Сохранить как, Сохранить копию, Сохранить всё, Вернуться, Импортировать, Экспортировать, Объединить проект, Информация о проекте, Печать, Предварительный просмотр, Экспортировать в PDF, Недавние файлы, Выход
- Правка: Отменить, Вернуть, Вырезать, Копировать, Вставить, Дублировать выбранное, Обновить, Выделить область, Box element selection, Выбрать всё, Удалить, Расположение, Выравнивание, Редактировать/закончить редактирование, Настройки
- Вид: Создать новый вид, Ортогональная проекция, Перспективная проекция, На весь экран, Стандартные виды (Уместить всё, Уместить выделенное, Isometric, Dimetric, Trimetric, Спереди, Сверху, Справа, Сзади, Снизу, Слева, Повернуть влево, Повернуть вправо), Freeze display (Save views, Load views, Freeze view, Clear views), Стиль представления (Как есть, Плоские линии, Shaded, Каркас, Точки, Скрытые линии, Без затенения), Bounding box, Стерео (Стерео красный/голубой, Четверная буферизация стерео, Стерео с чередованием строк, Стерео с чередованием столбцов, Выключить стерео, Выводить положения камеры), Масштаб (Увеличить, Уменьшить, Увеличить область), Окно документа (Закреплённое, Откреплённое, На весь экран), Показать/скрыть оси координат, Плоскость сечения, Текстурирование, Видимость (Видимость, Показать выделенные, Скрыть выделенные, Выбрать видимые объекты, Инвертировать все видимости, Показать все объекты, Скрыть все объекты, Откл/вкл выделяемость, Показывать замеры, Удалить замер), Навигация/редактирование, Внешний вид, Случайный цвет, Верстак, Панели инструментов (Файл, Верстак, Макрос, Вид, Структура, Навигация), Панели (Отчёт, Иерархия документа, Окно свойств, Просмотр выделения, Комбо панель, Консоль Python, DAG view), Tree view actions (Sync view, Sync selection, Sync placement, Pre-selection, Record selection, Single document, Multi document, Collapse/expand, Initiate dragging, Go to selection), Строка состояния
- Инструменты: Редактор параметров, Сохранить изображение, Инспектор сцены, Граф зависимостей, Project utility, Измерить расстояние, Text document, Поворотный просмотр, Конвертор величин, Настройка, Addon manager
- Макросы: Запись макроса, Остановить запись макроса, Макрос, Выполнить макрос, Отладка макросов, Остановить отладку, Шаг с обходом, Шаг с заходом, Установить/снять точку останова
- Окна: Следующее, Предыдущее, Плиткой, Каскадом, Окна
- Справка: Справка, Сайт FreeCAD, Пользовательская документация, Документация по созданию скриптов на Python, Автоматически сгенерированная документация Python, Форум FreeCAD, FreeCAD ЧаВо, О FreeCAD, Что это?
Документация пользователя
- Начинающим
- Установка: Загрузка, Windows, Linux, Mac,
Дополнительных компонентов, Docker, AppImage, Ubuntu Snap
- Базовая: О FreeCAD, Интерфейс, Навигация мыши, Методы выделения, Имя объекта, Настройки, Верстаки, Структура документа, Свойства, Помоги FreeCAD, Пожертвования
- Помощь: Учебники, Видео учебники
- Верстаки: Std Base, Arch, Assembly, CAM, Draft, FEM, Inspection, Mesh, OpenSCAD, Part, PartDesign, Points, Reverse Engineering, Robot, Sketcher, Spreadsheet, Surface, TechDraw, Test Framework