467,922 Members | 1,295 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,922 developers. It's quick & easy.

Python Importing and modifying print

Good Morning,

Is there a way for a function called within an _imported_
library to call back to _calling_ python program to run a
function? (Shown below)

Also can you overload the print function to have it do
redirect output to an array for a bit, and then switch
it back. (for example: right before importing make print
append each line to an array vice printing it, then going
back to normal after the import is complete.)

Many thanks!

#first_file.py
#!/usr/local/bin/python
import newlib
def main():
print 'hi'

#newlib.py
def go():
???????.main()
???????.main()
go()

#Desired results
% ./first_file.py
hi
hi
%
Jul 18 '05 #1
  • viewed: 1573
Share:
1 Reply
ke****@netacc.net (J. Kenney) wrote in
news:97**************************@posting.google.c om:
Good Morning,

Is there a way for a function called within an _imported_
library to call back to _calling_ python program to run a
function? (Shown below)
Yes, you *could* do that, see the code below: the script is loaded into a
module called __main__ so all you have to do is import __main__ and you can
access the scripts variables.
#newlib.py import __main__
def go():
__main__.main()
__main__.main()
go()

This still won't have quite the results you want, as the function main
doesn't exist at the point when you import the other module. You need to
define it before the import (remember, the code in a module is executed
the first time the module is imported):

#first_file.py
#!/usr/local/bin/python
def main():
print 'hi'

import newlib
However, you probably don't want to do that. A much better solution is
either to put your 'main' function into another module, or to pass the
callback function around as a parameter:

#first_file.py
import newlib

def main():
print 'gi'

newlib.go(main)

#newlib.py
def go(where):
where()
where()


Also can you overload the print function to have it do
redirect output to an array for a bit, and then switch
it back. (for example: right before importing make print
append each line to an array vice printing it, then going
back to normal after the import is complete.)

Yes, the easiest way would be to reassign sys.stdout to put output into
your array using cStringIO and then restore sys.stdout after you have
finished. Again though, it isn't a good idea to do real work on an import;
much better to do the work in a function and have no real code in the
imported module.

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Andrew Dalke | last post: by
4 posts views Thread by Michael Yanowitz | last post: by
11 posts views Thread by walterbyrd | last post: by
10 posts views Thread by sandipm | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.