Python Importing and modifying print

J

J. Kenney

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
%
 
D

Duncan Booth

(e-mail address removed) (J. Kenney) wrote in
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.
 

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
474,202
Messages
2,571,057
Members
47,665
Latest member
salkete

Latest Threads

Top