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
  • 43,610
  • 8
  • 84
  • 94
Arenim
  • 3,877
  • 3
  • 19
  • 30

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
  • 25,191
  • 47
  • 61
  • 93
Marc Mutz - mmutz
  • 23,707
  • 11
  • 74
  • 87
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,017
  • 1
  • 27
  • 38
  • 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