472,981 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,981 software developers and data experts.

Redirecting standard out in a single namespace

Hello,

I'm trying to redirect standard out in a single namespace.

I can replace sys.stdout with a custom object - but that affects all
namespaces.

There will be code running simultaneously that could import sys
afterwards - so I don't want to make the change in the sys module.

I have an idea to redefine __import__ for the relevant namespace - so
that an attempt to import sys will return a different module with a
custom object for stdout. As sys is a builtin module this might not
work for the print statement, which is what I want to redirect.

I'm not in a position to test my idea until later :

__import = __import__
def __import__(name):
if name == 'sys':
return __import('newsys')
else:
return __import(name)

import sys

Is there another way to shadow the sys module from a single namespace ?

All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

Jan 20 '06 #1
9 1718
Fuzzyman wrote:
Is there another way to shadow the sys module from a single namespace ?


I've never actually tried this, but try making a copy of the sys module
then replacing the stdout object with your own object. Then you can
replace "sys" of the namespace with your custom "sys" module. I guess it
would look something like this:

import mysys #My dummy sys module
import sys #Actual sys module

#Copy sys module into dummy sys module
mysys.__dict__.update(sys.__dict__)

#Replace stdout with custom stdout
mysys.stdout = MyStdout()

#Replace sys of namespace
namespace.sys = mysys
This seems like it should work, however I don't know if copying the
entire dictionary of one module to another is a safe thing to do.

-Farshid
Jan 20 '06 #2
I'm sorry, but i don't see how this will solve the problem? It is
exactly the same, only now you've replaced everything in sys except
just sys.stdout?
At any rate, perhapse the code you will write will be more maintainable
if instead of redirecting sys.stdout for some of the code just use a
different function (instead of print) for the times where you wish it
to be redirected somewhere else? it will probably make your code
longer, but the maintainer will have one less "gotcha" to worry about a
few months/years down the road. perhapse it is best to not do the
"clever" thing this time ;-) ?

Jan 20 '06 #3

Ido Yehieli wrote:
I'm sorry, but i don't see how this will solve the problem? It is
exactly the same, only now you've replaced everything in sys except
just sys.stdout?
In the solution above (which I haven't had a chance to test) you're
just chaning hte reference to sys to point to a different module, so
you're not messing with sys itself. This won't affect other code that
uses the sys module.

Because of the builtin status of the sys module I'm not *convinced* it
will work. I'll try it though.
At any rate, perhapse the code you will write will be more maintainable
if instead of redirecting sys.stdout for some of the code just use a
different function (instead of print) for the times where you wish it
to be redirected somewhere else? it will probably make your code
longer, but the maintainer will have one less "gotcha" to worry about a
few months/years down the road. perhapse it is best to not do the
"clever" thing this time ;-) ?


We're executing code from another module that uses the print statement
a lot. That module isn't our code - other wise we wouldn't have a
problem. :-)

Changing the module will mean a great deal more to maintain, not less.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

Jan 21 '06 #4
oh, ok...
I guess people have to learn to use a logger instead of print in
production code...

Jan 21 '06 #5
On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <fu******@gmail.com> wrote:
Hello,

I'm trying to redirect standard out in a single namespace.

I can replace sys.stdout with a custom object - but that affects all
namespaces.

There will be code running simultaneously that could import sys
afterwards - so I don't want to make the change in the sys module.

I have an idea to redefine __import__ for the relevant namespace - so
that an attempt to import sys will return a different module with a
custom object for stdout. As sys is a builtin module this might not
work for the print statement, which is what I want to redirect.

I'm not in a position to test my idea until later :

__import = __import__
def __import__(name):
if name == 'sys':
return __import('newsys')
else:
return __import(name)

import sys

Is there another way to shadow the sys module from a single namespace ?

It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?

Regards,
Bengt Richter
Jan 23 '06 #6

Bengt Richter wrote:
On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <fu******@gmail.com> wrote:
Hello,

I'm trying to redirect standard out in a single namespace.

I can replace sys.stdout with a custom object - but that affects all
namespaces.

There will be code running simultaneously that could import sys
afterwards - so I don't want to make the change in the sys module.

I have an idea to redefine __import__ for the relevant namespace - so
that an attempt to import sys will return a different module with a
custom object for stdout. As sys is a builtin module this might not
work for the print statement, which is what I want to redirect. [snip..]Is there another way to shadow the sys module from a single namespace ?
It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?


I've just tried checking __name__ in my custom stdout object.
Unfortunately __name__ is always the module in which the new stdout
object lives.

In theory I could go up (down?) the stack to the previous frame and
check __name__ there - but it sounds like a hack.

Any other ways of checking where sys.stdout is called from ?

All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
Regards,
Bengt Richter


Jan 23 '06 #7

Bengt Richter wrote:
On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <fu******@gmail.com> wrote:
Hello,

I'm trying to redirect standard out in a single namespace.

I can replace sys.stdout with a custom object - but that affects all
namespaces.

There will be code running simultaneously that could import sys
afterwards - so I don't want to make the change in the sys module.

I have an idea to redefine __import__ for the relevant namespace - so
that an attempt to import sys will return a different module with a
custom object for stdout. As sys is a builtin module this might not
work for the print statement, which is what I want to redirect.
[snip..]
Is there another way to shadow the sys module from a single namespace ?
It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?


Redirecting stderr is identical in concept to redirecting stdout.

The following in the write method of the custom out object works :

sys._getframe(1).f_globals['__name__']

sys.stdout.write is *always* called from at least one frame deep in the
stack - so it works.

However the Python docs say of sys._getframe :

This function should be used for internal and specialized purposes
only.

Might this approach be brittle ?

All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
Regards,
Bengt Richter


Jan 23 '06 #8
On 23 Jan 2006 04:00:40 -0800, "Fuzzyman" <fu******@gmail.com> wrote:

Bengt Richter wrote:
[...]
It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?


Redirecting stderr is identical in concept to redirecting stdout.

Yeah, just reminding, in case you need to do that too ;-)
The following in the write method of the custom out object works :

sys._getframe(1).f_globals['__name__']

sys.stdout.write is *always* called from at least one frame deep in the
stack - so it works. Yes, that's about what I had in mind, not being able to think of an alternative
(other than the obvious one of using something other than print in the module
where you want to redirect, either by hand or by effective source rewrite one way
or another to translate print statments into e.g. myprint('the', 'print', 'args') or such.
You could do source preprocessing or translating at the AST level, or you could do byte code munging.
Nothing too nice.

However the Python docs say of sys._getframe :

This function should be used for internal and specialized purposes
only.

Might this approach be brittle ?

In what sense? I guess it ought to work for the version it's defined for, but the advice is there.
Maybe we can get something more specific from the author of the above doc snippet ;-)

Regards,
Bengt Richter
Jan 24 '06 #9

Bengt Richter wrote:
[snip..]
The following in the write method of the custom out object works :

sys._getframe(1).f_globals['__name__']

sys.stdout.write is *always* called from at least one frame deep in the
stack - so it works. Yes, that's about what I had in mind, not being able to think of an alternative
(other than the obvious one of using something other than print in the module
where you want to redirect, either by hand or by effective source rewrite one way
or another to translate print statments into e.g. myprint('the', 'print', 'args') or such.
You could do source preprocessing or translating at the AST level, or you could do byte code munging.
Nothing too nice.

However the Python docs say of sys._getframe :

This function should be used for internal and specialized purposes
only.

Might this approach be brittle ?

In what sense? I guess it ought to work for the version it's defined for, but the advice is there.
Maybe we can get something more specific from the author of the above doc snippet ;-)


``inspect.currentframe`` has no such warning. The equivalent would then
be :

inspect.currentframe().f_back.f_globals['__name__']

I guess unless the implementation of Python changes that will continue
to work. :-)

Thanks

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
Regards,
Bengt Richter


Jan 24 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Matt Burland | last post by:
I'm having a problem with redirecting the StandardOutput of a process that I use to run a DOS program in my application. The problem is that I when I start my process (which I do in a separate...
32
by: toolmaster | last post by:
Since many of the modern computer languages have built-in namespace features, I can't understand why not add this feature into standard C. I've heard many people complain of the lacking of...
1
by: Gaijinco | last post by:
Hi! I was coding something which had some lines like these: int main(){ int n; scanf("%d",&n); fflush(stdin); int* ans = new int; int idx=0;
9
by: PengYu.UT | last post by:
Hi, I feel argparse has some useful things that optparse doesn't have. But I can't find it argparse in python library reference. I'm wondering when it will be available in the python standard...
22
by: Chris Thomasson | last post by:
I am thinking about using this technique for all the "local" memory pools in a paticular multi-threaded allocator algorithm I invented. Some more info on that can be found here: ...
4
by: dustin | last post by:
I've been hacking away on this PEP for a while, and there has been some related discussion on python-dev that went into the PEP: ...
0
by: kreismaler | last post by:
I have some problems to understand the difference of using the STDOUT and using "anonymous pipes" as shown below: using System; using System.Diagnostics; using System.IO; namespace...
0
by: darrel | last post by:
I'm trying to set up a web.config file (2.0) so that all 404 errors are redirected to another page. What happens instead of the redirect, however, is that the browser tries loading the actual...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.