Python Importing and modifying print

Duncan Booth me at privacy.net
Wed Jan 28 07:36:59 EST 2004


kenney at netacc.net (J. Kenney) wrote in 
news:9742a725.0401280426.329d2178 at posting.google.com:

> 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.




More information about the Python-list mailing list