Console Python#

O Python Console é uma maneira rápida de executar comandos, com acesso a toda a API do Python, histórico de comandos e preenchimento automático. O prompt de comando é típico do Python 3.x, o intérpretador é carregado e está pronto para aceitar comandos no prompt `` >>> ``.

The Python Console is a good way to explore the possibilities of Blender built-in Python. The Python Console can be used to test small bits of Python code which can then be pasted into larger scripts.

../_images/editors_python-console_default.png

Python Console.#

Interface#

Os menus dos cabeçalhos#

View Menu#

Zoom In / Zoom Out

Increases/Decreases the font size of the console text.

Move to Previous Word Ctrl-Left

Moves the cursor to the beginning of the previous word. If the cursor is in the middle of a word, the cursor is moved to the beginning of the current word.

Move to Next Word Ctrl-Right

Moves the cursor to the end of the next word. If the cursor is in the middle of a word, the cursor is moved to the end of the current word.

Move to Line Begin Home

Moves the cursor to the start of the current line.

Shift-Home: Selects all text between the cursor and the start of the current line.

Move to Line End End

Moves the cursor to the end of the current line.

Shift-End: Selects all text between the cursor and the end of the current line.

Console Menu#

Clear All

Refreshes the console giving the view a fresh start. Note that command history is not cleared.

Clear Line Shift-Return.

Removes everything from the prompt line.

Delete Previous Word Ctrl-Backspace

Deletes everything between the cursor and the beginning of the previous word (separated by periods). If the cursor is in the middle of a word, deletes everything to the beginning of the current word.

Delete Next Word Ctrl-Delete

Deletes everything between the cursor and the end of the next word. If the cursor is in the middle of a word, deletes everything to the end of the current word.

Copy as Script Shift-Ctrl-C

Copies the full history buffer to the clipboard, this can be pasted into a text file to be used as a Python script.

Recortar Ctrl-X

Deletes the selected text and copies it to the clipboard.

Copiar Ctrl-C

Copia a seleção.

Colar Ctrl-V

Cola na linha de comando

Indent Tab

Inserts a tab character at the cursor.

Unindent Shift-Tab

Unindents the selection.

Backward in History Up

Changes the current command to previous command as they appear in the command history.

Forward in History Down

Changes the current command to next command as they appear in the command history.

Autocomplete Tab

See Auto Completion for more information.

Main View#

Atalhos vinculados

  • LMB – Moves the cursor along the input line.

  • Seta à esq. / Seta à dir. – Movimenta o cursor.

  • Ctrl-Seta à esq. / Ctrl-Seta à dir. – Movimenta o cursor, saltando entre palavas.

  • Shift-Left / Shift-Right – Selects characters to the left/right.

  • Shift-Ctrl-Left / Shift-Ctrl-Right – Selects words to the left/right.

  • Ctrl-A Select all text and text history.

  • Backspace / Delete – Apaga os caracteres.

  • Ctrl-Backspace / Ctrl-Delete – Apaga as palavras.

  • Return – Execute command.

  • Shift-Enter – Adiciona ao histórico de comandos sem executar.

Usage#

Apelidos#

Algumas variáveis e módulos estão disponíveis para conveniência:

  • C: Fornece acesso rápido a bpy.context.

  • D: Fornece acesso rápido a bpy.data.

  • bpy: O módulo de nível mais alto da API Python do Blender.

Primeiro olhar sobre o ambiente de console#

Para verificar o que foi carregado dentro do ambiente do interpretador, digite dir() diretamente no prontuário e execute.

../_images/editors_python-console_dir.png

Completar automaticamente#

Agora, digite bpy. e então pressione Tab e você irá ver a funcionalidade auto-completar do console em ação.

../_images/editors_python-console_completion.png

You will notice that a list of submodules inside of bpy appear. These modules encapsulate all that we can do with Blender Python API and are very powerful tools.

Vamos listar todos os conteúdos do módulo bpy.app.

Observe a saída verde acima do prompt em que você ativou o preenchimento automático. O que você vê é o resultado da listagem de preenchimento automática. Na lista acima, todos são nomes atribuídos ao módulo, mas se você vir algum nome terminado com `` (``, essa é uma função.

Nós faremos uso disto um bocado para ajudar você a aprender a nossa API mais rapidamente. Agora que você colocou as mãos e já tem uma noção sobre o assunto, vamos proceder com a investigação de alguns módulos presentes dentro do bpy.

Antes de brincar um pouco com os módulos#

Se você olhar na 3D Viewport na scene padrão do Blender, você notará três objetos: Cube, Light and Camera.

  • Todos os objetos existem em um contexto e podem haver diversos modos sob os quais eles poderão ser operados.

  • Em qualquer instância, somente um objeto estará ativo e pode haver mais de um objeto selecionado.

  • Todos os objetos são referenciados como dados dentro do arquivo Blender.

  • Existem operadores e funções que criam e modificam estes objetos.

Para todos os cenários listados acima (nem todos foram listados, há mais e pense em quantos…) o módulo bpy provê funcionalidade para acessar e modificar dados.

Examples#

bpy.context#

Nota

Para que os comandos listados abaixo mostrem a saída apropriada, certifique-se de ter objetos selecionados na 3D viewport.

../_images/editors_python-console_bpy-context.png
bpy.context.mode

Irá imprimir o modo atual da 3D Viewport (Object, Edit, Sculpt, etc.).

bpy.context.object ou bpy.context.active_object

Irá fornecer a você, acesso ao objeto ativo na janela 3D Viewport.

Change the X location to a value of 1:

bpy.context.object.location.x = 1

Move o objeto a partir de sua localização prévia 0,5 unidades no eixo X:

bpy.context.object.location.x += 0.5

Altera a localização X, Y, Z:

bpy.context.object.location = (1, 2, 3)

Altera somente os componentes X e Y:

bpy.context.object.location.xy = (1, 2)

Tipo de dados da localização dos objetos:

type(bpy.context.object.location)

Agora, há bastante dados que fornecem a você acesso a:

dir(bpy.context.object.location)
bpy.context.selected_objects

Irá fornecer acesso a uma lista de todos os objetos selecionados.

Digite isto e então pressione Tab:

bpy.context.selected_objects

Para imprimir o nome do primeiro objeto dentro da lista:

bpy.context.selected_objects[0]

The complex one… But this prints a list of selected objects not including the active object::

[obj for obj in bpy.context.selected_objects if obj != bpy.context.object]

bpy.data#

bpy.data possui funções e atributos que irão fornecer acesso a todos os dados dentro do arquivo Blender.

Você pode acessar os seguintes dados dentro do arquivo Blender atual: objetos, malhas, materiais, texturas, cenas, telas, sons, scripts, etc.

São bastante dados.

../_images/editors_python-console_bpy-data.png

bpy.ops#

O sistema de ferramentas é construído em torno do conceito de operadores. Os operadores são tipicamente executados a partir dos botões ou menus que podem ser chamados diretamente também a partir da linguagem de programação Python.

See the bpy.ops API documentation for a list of all operators.