Changes between Version 63 and Version 64 of DeveloperGuidelines/CodeConventions


Ignore:
Timestamp:
01/20/18 21:17:16 (7 years ago)
Author:
Dominic König
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • DeveloperGuidelines/CodeConventions

    v63 v64  
    2424{{{
    2525python static/scripts/tools/pep8.py yourfile.py
     26}}}
     27
     28=== Print Statements ===
     29
     30For compatibility with WSGI as well as newer web2py (>=2.15), using the {{{print}}} statement in web application sources is strongly discouraged.
     31
     32CLI scripts containing print statements will even crash since gluon/shell.py now future-imports the Python-3 print_function.
     33
     34For 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
     39For 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
     43Using {{{sys.std*.write()}}} (remember that write expects string/bugger, so must convert explicitly):
     44{{{#!python
     45import sys
     46
     47# For status/error/debug messages:
     48sys.stderr.write("Here is a status message\n")
     49
     50# For results:
     51sys.stdout.write("%s\n" % result)
     52}}}
     53
     54Using the logger:
     55{{{#!python
     56from gluon import current
     57
     58# Use this for any permanent message output in server scripts:
     59current.log.error("Here is an error message")
     60}}}
     61
     62If neither of the above is possible, import+use the print-function:
     63{{{
     64# This must be the first statement in the file:
     65from __future__ import print_function
     66
     67# Then use the print-function:
     68print("The print-function", "accepts", "multiple arguments")
     69
     70# Remember that server code must write to stderr, not stdout:
     71print("Direct output to stderr", file=sys.stderr)
    2672}}}
    2773