944,172 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 3991
  • Python RSS
0

A Print function for different versions of python

by on Dec 20th, 2008
This snippet defines a Print function which can be used with python 2.4, 2.5, 2.6 and 3.0 (for 3.0 this is just the built-in print function). It's interface is that of the python 3.0's print. It simplifies the task of writing transitional code which runs under python 2.5 and python 3.0.
Python Code Snippet (Toggle Plain Text)
  1. # module cbprint
  2. # (C) 2008 Gribouillis at www.daniweb.com
  3.  
  4. """This module defines a Print function to use with python 2.x or 3.x.
  5.  
  6. Usage:
  7. from cbprint import Print
  8. Print("hello", "world")
  9.  
  10. It's interface is that of python 3.0's print. See
  11. http://docs.python.org/3.0/library/functions.html?highlight=print#print
  12. """
  13. __all__ = ["Print"]
  14. import sys
  15. try:
  16. Print = eval("print") # python 3.0 case
  17. except SyntaxError:
  18. try:
  19. D = dict()
  20. exec("from __future__ import print_function\np=print", D)
  21. Print = D["p"] # 2.6 case
  22. del D
  23. except SyntaxError:
  24. del D
  25. def Print(*args, **kwd): # 2.4, 2.5, define our own Print function
  26. fout = kwd.get("file", sys.stdout)
  27. w = fout.write
  28. if args:
  29. w(str(args[0]))
  30. sep = kwd.get("sep", " ")
  31. for a in args[1:]:
  32. w(sep)
  33. w(str(a))
  34. w(kwd.get("end", "\n"))
Comments on this Code Snippet
Feb 8th, 2009
0

Re: A Print function for different versions of python

where would you put this to have it as a built in function?
i have python 2.5 but it says python2.4.6 if that helps
Posting Pro in Training
leegeorg07 is offline Offline
428 posts
since Jul 2008
Message:
Previous Thread in Python Forum Timeline: I need help please
Next Thread in Python Forum Timeline: multi - platform ides





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC