Console Python

The Python Console is a quick way to execute commands, with access to the entire Python API, command history and auto-complete. The command prompt is typical for Python 3.x, the interpreter is loaded and is ready to accept commands at the 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

Header Menus

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.

Move to Line End End

Moves the cursor to 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.

Copy Ctrl-C

Copy the selection.

Paste Ctrl-V

Paste into the command line.

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

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

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

  • 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.

Utilização

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

Now, type bpy. and then press Tab and you will see the Console auto-complete feature in action.

../_images/editors_python-console_completion.png

Você irá notar que uma lista de sub-módulos presentes dentro do bpy irá aparecer. Estes módulos encapsulam tudo o que podemos fazer com a API Python do Blender e são ferramentas bastante poderosas.

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

Notice the green output above the prompt where you enabled auto-completion. What you see is the result of auto completion listing. In the above listing all are module attributed names, but if you see any name end with (, then that is a function.

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

If you look at the 3D View in the default Blender scene, you will notice three objects: 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.

Exemplos

bpy.context

Nota

Para que os comandos listados abaixo mostrem a saída apropriada, certifique-se de ter objetos selecionados dentro da janela de visualização 3D.

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

Irá imprimir o modo atual da janela de visualização 3D (Objeto, Edição, Escultura, etc.).

bpy.context.object or bpy.context.active_object

Will give you access to the active object in the 3D View.

Change the X location to a value of 1:

bpy.context.object.location.x = 1

Move the object from previous X location by 0.5 unit:

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

Change the X, Y, Z location:

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

Altera somente os componentes X e Y:

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

The data type of object’s location:

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.

Type this and then press Tab:

bpy.context.selected_objects

Para imprimir o nome do primeiro objeto dentro da lista:

bpy.context.selected_objects[0]

A parte um pouco mais complexa… Mas isso imprime uma lista de objetos que não incluem o objeto ativo:

[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.