| 26 | }}} |
| 27 | |
| 28 | === Print Statements === |
| 29 | |
| 30 | For compatibility with WSGI as well as newer web2py (>=2.15), using the {{{print}}} statement in web application sources is strongly discouraged. |
| 31 | |
| 32 | CLI scripts containing print statements will even crash since gluon/shell.py now future-imports the Python-3 print_function. |
| 33 | |
| 34 | For everything that is to be executed in the restricted environment (i.e. all server code): |
| 35 | - use sys.stderr.write() |
| 36 | - better yet (and mandatory for any permanent debug/error messages): use {{{current.log.*}}}, as it can be turned on/off centrally, and routed to a log file |
| 37 | - if absolutely necessary, add the future-import to the file and use the print-function |
| 38 | |
| 39 | For CLI scripts: |
| 40 | - use sys.stderr.write() for status/error messages, or sys.stdout.write() for results |
| 41 | - alternatively, add the future-import to the script and use the print-function |
| 42 | |
| 43 | Using {{{sys.std*.write()}}} (remember that write expects string/bugger, so must convert explicitly): |
| 44 | {{{#!python |
| 45 | import sys |
| 46 | |
| 47 | # For status/error/debug messages: |
| 48 | sys.stderr.write("Here is a status message\n") |
| 49 | |
| 50 | # For results: |
| 51 | sys.stdout.write("%s\n" % result) |
| 52 | }}} |
| 53 | |
| 54 | Using the logger: |
| 55 | {{{#!python |
| 56 | from gluon import current |
| 57 | |
| 58 | # Use this for any permanent message output in server scripts: |
| 59 | current.log.error("Here is an error message") |
| 60 | }}} |
| 61 | |
| 62 | If neither of the above is possible, import+use the print-function: |
| 63 | {{{ |
| 64 | # This must be the first statement in the file: |
| 65 | from __future__ import print_function |
| 66 | |
| 67 | # Then use the print-function: |
| 68 | print("The print-function", "accepts", "multiple arguments") |
| 69 | |
| 70 | # Remember that server code must write to stderr, not stdout: |
| 71 | print("Direct output to stderr", file=sys.stderr) |