4
$\begingroup$

How can I run some script and have print result in console window? Now I have these results only in System Console Window. enter image description here

$\endgroup$
0

1 Answer 1

12
$\begingroup$

Override print method.


Been investigating a number of ways to do this. Possibly the simplest is to override the print in your scripts. Below is designed to from somewhere import print and writes all print non keyword arguments to open consoles in same screen.

import bpy
from bpy import context

import builtins as __builtin__

def console_print(*args, **kwargs):
    for a in context.screen.areas:
        if a.type == 'CONSOLE':
            c = {}
            c['area'] = a
            c['space_data'] = a.spaces.active
            c['region'] = a.regions[-1]
            c['window'] = context.window
            c['screen'] = context.screen
            s = " ".join([str(arg) for arg in args])
            for line in s.split("\n"):
                bpy.ops.console.scrollback_append(c, text=line)

def print(*args, **kwargs):
    """Console print() function."""

    console_print(*args, **kwargs) # to py consoles
    __builtin__.print(*args, **kwargs) # to system console

print("print me to console")
print("and me\n and me", "and me\nI'm:", print)  

![enter image description here

My attempts at redirecting stdio have failed and often lock up a console. Will get back to this later with better links, but there is a lot of console code to fiddle around with ... console_python.py bl_operators/console.py and the mathviz addon code.

EDIT: See Dubplicate Question Answer on handling stdio redirecting.

$\endgroup$
1
  • $\begingroup$ This can also be improved by writing the script to a seperated pyconsole.py file, which is in the path of sys.path (e.g. %APPDATA%\Blender Foundation\Blender\<version>\scripts\addons) in Blender, and then use from pyconsole import print in the script. $\endgroup$
    – Hansimov
    May 29, 2021 at 13:07

Not the answer you're looking for? Browse other questions tagged .