4

When I call this code:

QScriptEngine e;
e.evaluate("print('hello, world!')");

the output text (from print method) is written to main application's terminal.

Is there any way to redirect it to a custom QIODevice?

ismail
  • 46,010
  • 9
  • 86
  • 95
Arenim
  • 4,097
  • 3
  • 21
  • 31

2 Answers2

5

You can replace print() with your own implementation:

First, define a C++ function that does what you want. In this case, it's just empty for exposition:

QScriptValue myPrint( QScriptContext * ctx, QScriptEngine * eng ) {
    return QScriptValue();
}

Then install that function as your new print():

QScriptEngine e = ...;
e.globalObject().setProperty( "print", e.newFunction( &myPrint ) );
e.evaluate( "print(21);" ); // prints nothing
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
1

The output text goes to stdout, so you need to redirect stdout. For ideas see this question. Best ideas: use reopen to redirect to a FILE*, or (better) use rdbuf to redirect stdout to some other stream derived from std::ostream, and you could play with QFile.open(1,...)-

Community
  • 1
  • 1
hmuelner
  • 8,093
  • 1
  • 28
  • 39
  • There are a lots of texts, going to stdout (QWarnings, QDebug to stderr, other printf/scanf etc). I need to redirect only output of QScriptEngine... – Arenim Jan 07 '11 at 12:22