Changing default output object for

G

Graham Dumpleton

I am sure someone has probably thought of this and there are good
reasons why it is a bad idea or not possible, but, is there any
technical reason why one couldn't somehow replace PRINT_ITEM byte
code, with combination of byte codes which inserted in a reference to
a file like object and then invoked PRINT_ITEM_TO byte code instead.

In other words, the aim is allow users code to use 'print' but change
where the output goes when no target file is provided.

I do know that one can replace sys.stdout with another file object in
the simple case, or in the more complicated case with a file like
object that determines where to redirect output based on the calling
thread identity or some over criteria, but wanted to see if some one
could do something without modifying sys.stdout.

One particular example where I thought this might be interesting is to
allow in a web templating system where Python code blocks can be
embedded in markup, the use of the 'print' statement without a user
having to know that they really need to direct output to a special
file object, eg. 'print >> response'. Procedure might thus be to load
Python code snippets and compile to byte code. Fixup byte code to
change PRINT_ITEM to PRINT_ITEM_TO with other byte codes added to
insert appropriate reference to file like object being supplied
through data only passed to code object when executed. Cache code for
ongoing use. Invoke code object as required, supplying reference to
file object for output.

In some template systems such as in web.py they replace sys.stdout
with a magic object which based on the identity of the thread making
calls to the methods of sys.stdout, will redirect the output back to a
registered response object, but instead of doing it this way, could
byte code manipulation provide another way.

Anyway, just curious as to whether it would be possible or not and if
someone has an example of doing it using byteplay or similar would
love to see what is required.

Graham
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top