├── MANIFEST.in ├── setup.cfg ├── .gitignore ├── Makefile ├── .github └── workflows │ └── ci.yml ├── setup.py ├── README.md ├── CODESHELTER.md ├── test └── test_basic.py ├── LICENSE └── q.py /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | [bdist_wheel] 4 | universal=1 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | MANIFEST 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | # MacOS garbage 39 | .DS_Store 40 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | TESTS = $(wildcard test/test_*.py) 2 | 3 | .PHONY: deps pycodestyle test build push clean 4 | 5 | all: pycodestyle test build 6 | 7 | deps: 8 | # q doesn't have any *runtime* dependencies. 9 | # These dependencies are only needed for development. 10 | pip install pycodestyle 11 | pip install wheel 12 | 13 | pycodestyle: 14 | @echo === Running pycodestyle on files 15 | pycodestyle $(wildcard *.py) $(wildcard test/*.py) 16 | 17 | test: 18 | @echo 19 | @ $(foreach TEST,$(TESTS), \ 20 | ( \ 21 | echo === Running test: $(TEST); \ 22 | python $(TEST) || exit 1 \ 23 | )) 24 | 25 | build: 26 | python setup.py sdist 27 | python setup.py bdist_wheel 28 | 29 | push: build 30 | python setup.py sdist upload 31 | python setup.py bdist_wheel upload 32 | 33 | clean: 34 | rm -rf build dist q.egg-info 35 | find -name *.pyc -delete 36 | @- git status 37 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | tests: 7 | runs-on: ubuntu-20.04 8 | strategy: 9 | matrix: 10 | python-version: 11 | - "2.7" 12 | - "3.5" 13 | - "3.6" 14 | - "3.7" 15 | - "3.8" 16 | - "3.9" 17 | - "3.10" 18 | - "3.11" 19 | - "3.12" 20 | - pypy3.7 21 | - pypy3.8 22 | - pypy3.9 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | 27 | - name: Set up Python ${{ matrix.python-version }} 28 | if: matrix.python-version != '2.7' 29 | uses: actions/setup-python@v4 30 | with: 31 | python-version: ${{ matrix.python-version }} 32 | - name: Set up Python 2.7 33 | if: matrix.python-version == '2.7' 34 | run: | 35 | sudo apt-get update 36 | sudo apt-get install -y python2.7 python2.7-dev 37 | sudo ln -sf python2.7 /usr/bin/python 38 | curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py 39 | python get-pip.py 40 | rm get-pip.py 41 | 42 | - name: Install dependencies 43 | run: | 44 | python -m pip install --upgrade pip setuptools wheel pycodestyle 45 | - name: Run tests 46 | run: make pycodestyle test 47 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open('README.md') as f: 4 | readme = f.read() 5 | 6 | setup( 7 | name='q', version='2.7', py_modules=['q'], 8 | description='Quick-and-dirty debugging output for tired programmers', 9 | long_description=readme, long_description_content_type='text/markdown', 10 | author='Ka-Ping Yee', author_email='ping@zesty.ca', 11 | license='Apache License 2.0', 12 | classifiers=[ 13 | "Programming Language :: Python", 14 | "Programming Language :: Python :: 2.7", 15 | "Programming Language :: Python :: 3", 16 | "Programming Language :: Python :: 3.3", 17 | "Programming Language :: Python :: 3.4", 18 | "Programming Language :: Python :: 3.5", 19 | "Programming Language :: Python :: 3.6", 20 | "Programming Language :: Python :: 3.7", 21 | "Programming Language :: Python :: 3.8", 22 | "Programming Language :: Python :: 3.9", 23 | "Programming Language :: Python :: 3.10", 24 | "Programming Language :: Python :: 3.11", 25 | "Programming Language :: Python :: Implementation :: PyPy", 26 | "Programming Language :: Python :: Implementation :: Jython", 27 | "Intended Audience :: Developers", 28 | "License :: OSI Approved :: Apache Software License", 29 | ], 30 | keywords=['debugging'], 31 | url='http://github.com/zestyping/q' 32 | ) 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # q 2 | 3 | [![Code Shelter](https://www.codeshelter.co/static/badges/badge-flat.svg)](https://www.codeshelter.co/) 4 | 5 | Quick and dirty debugging output for tired programmers. 6 | 7 | For a short demo, watch the [Lightning Talk](http://pyvideo.org/video/1858/sunday-evening-lightning-talks#t=25m15s) from PyCon 2013. 8 | 9 | Install q with `pip install -U q`. 10 | 11 | All output goes to `/tmp/q` (or on Windows, to `$HOME/tmp/q`). You can 12 | watch the output with this shell command while your program is running: 13 | 14 | tail -f /tmp/q 15 | 16 | To print the value of foo, insert this into your program: 17 | 18 | import q; q(foo) 19 | 20 | To print the value of something in the middle of an expression, you can 21 | wrap it with `q()`. You can also insert `q/` or `q|` into the expression; 22 | `q/` binds tightly whereas `q|` binds loosely. For example, given this 23 | statement: 24 | 25 | file.write(prefix + (sep or '').join(items)) 26 | 27 | you can print out various values without using any temporary variables: 28 | 29 | file.write(prefix + q(sep or '').join(items)) # prints (sep or '') 30 | file.write(q/prefix + (sep or '').join(items)) # prints prefix 31 | file.write(q|prefix + (sep or '').join(items)) # prints the arg to write 32 | 33 | To trace a function (showing its arguments, return value, and running time), 34 | insert this above the def: 35 | 36 | import q 37 | @q 38 | 39 | To start an interactive console at any point in your code, call q.d(): 40 | 41 | import q; q.d() 42 | 43 | By default the output of q is not truncated, but it can be truncated by calling: 44 | 45 | q.short 46 | 47 | Truncation can be reversed by: 48 | 49 | ```python 50 | q.long # Truncates output to 1,000,000 51 | q.long = 2000000 # Truncates output to 2,000,000 52 | ``` 53 | # Other projects inspired by this one 54 | 55 | * [`q` for golang](https://github.com/y0ssar1an/q) 56 | * [`qq` for elixir](https://github.com/mandarvaze/q) 57 | * [`ic` for Python](https://github.com/gruns/icecream) - Similar library for Python, inspired by `q`. 58 | 59 | The following 60 | [Lightning Talk](http://pyvideo.org/video/1858/sunday-evening-lightning-talks#t=25m15s) 61 | shows how powerful using q can be. 62 | -------------------------------------------------------------------------------- /CODESHELTER.md: -------------------------------------------------------------------------------- 1 | ## Note to Code Shelter maintainers 2 | 3 | Thank you so much for contributing to the maintenance of this project! 4 | I hope it can continue to be useful to you and to others. 5 | 6 | ### Involvement 7 | 8 | Several people still find `q` useful, but I haven't been available 9 | to keep up with the GitHub issues for some time. I'm grateful to 10 | Code Shelter maintainers for help fielding these issues. 11 | 12 | I would like to continue to be consulted on design decisions. 13 | Because I have not been responsive, though, it is reasonable to 14 | do this in a way that doesn't block progress. 15 | My suggestion would be to notify me with a limited response window: 16 | notify me, let me know when you'd like a response, and let me know 17 | what will happen if I don't respond. 18 | I'd appreciate being notified in this way when a design discussion 19 | is taking place or when a previously discussed plan changes substantially. 20 | 21 | ### Philosophy 22 | 23 | Because I have not been available to do the work, it isn't fair to 24 | expect that all decisions will be made in exactly the way I would 25 | make them. Nonetheless, I thought it wouldn't hurt to share the 26 | original intentions behind it as a guideline, in case you share my 27 | wish to keep it on that track: 28 | 29 | `q` is supposed to be *minimal*, *convenient*, and *predictable*. 30 | 31 | Minimal: Its one job is to give you visibility into what's happening 32 | in your program as it runs, and it should focus on doing that job well. 33 | 34 | Convenient: The barrier to using `q` should be kept low. If it's 35 | tedious to use, no one will bother to use it. Instrumenting a program 36 | with `q` should require a minimum of thinking and typing. 37 | 38 | Predictable: The behaviour of `q` must be easy to understand. 39 | Predictability of behaviour is vital for a debugging tool, much 40 | more so than for other programs. There is room for some fanciness 41 | in how values and data strucures are formatted for display, but 42 | it is imperative that the output be unambiguous. There should be 43 | very little distance between the output and reality — you don't 44 | want to have to think hard about why `q` is printing some things 45 | and not others or why it is generating output in a particular way. 46 | 47 | My greatest fear for the project is that the temptation to satisfy 48 | every feature request will lead to complicated behaviour and a 49 | multiplicity of configuration options. One of the main strengths 50 | of `q` is its *lack* of configuration options. 51 | If you have to troubleshoot the configuration options to figure out 52 | why it isn't doing what you expect, that defeats the whole point; 53 | a debugging tool is supposed to help you debug your program, not 54 | become another component that you also have to debug. 55 | 56 | As a canary test, if `q` one day has a configuration file, in my 57 | opinion, something has gone wrong. Having to locate such a file, 58 | define its format, and specify its options is far beyond the 59 | level of complexity I'd ideally want. 60 | 61 | ### Releases 62 | 63 | Code Shelter is authorized to maintain this project on PyPI; feel free 64 | to do releases when needed. Testing is automated with Github Actions. 65 | 66 | Thank you! 67 | 68 | 69 | —Ping 70 | -------------------------------------------------------------------------------- /test/test_basic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # vim: set ts=4 sw=4 et sts=4 ai: 3 | # 4 | # Test some basic functionality. 5 | # 6 | 7 | import os 8 | import re 9 | import sys 10 | import unittest 11 | 12 | qpath = os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')) 13 | sys.path.insert(0, qpath) 14 | import q 15 | Q_PATH = q.OUTPUT_PATH 16 | 17 | 18 | class TestQBasic(unittest.TestCase): 19 | 20 | def setUp(self): 21 | if os.path.exists(Q_PATH): 22 | os.remove(Q_PATH) 23 | 24 | def tearDown(self): 25 | self.setUp() 26 | 27 | def assertInQLog(self, string): 28 | # Check the log file exists. 29 | self.assertTrue(os.path.exists(Q_PATH)) 30 | 31 | # Read in the data. 32 | f = open(Q_PATH, 'r') 33 | logdata = f.read() 34 | f.close() 35 | 36 | # Check the string is found in the log file. 37 | # We can't use self.assertRegexpMatches as we need re.DOTALL 38 | expected_regexp = re.compile('.*%s.*' % string, re.DOTALL) 39 | if not expected_regexp.search(logdata): 40 | msg = '%s: %r not found in\n%s\n%s\n%s' % ( 41 | "Regexp didn't match", 42 | expected_regexp.pattern, 43 | "-"*75, 44 | logdata, 45 | "-"*75, 46 | ) 47 | raise self.failureException(msg) 48 | 49 | def test_q_log_message(self): 50 | import q 51 | q.q('Test message') 52 | self.assertInQLog('Test message') 53 | 54 | def test_q_function_call(self): 55 | import q 56 | 57 | @q.t 58 | def test(arg): 59 | return 'RetVal' 60 | 61 | self.assertEqual('RetVal', test('ArgVal')) 62 | 63 | self.assertInQLog('ArgVal') 64 | self.assertInQLog('RetVal') 65 | 66 | def test_q_argument_order_arguments(self): 67 | import q 68 | q.writer.color = False 69 | 70 | class A: 71 | def __init__(self, two, three, four): 72 | q(two, three, four) 73 | 74 | A("ArgVal1", "ArgVal2", "ArgVal3") 75 | self.assertInQLog(".*".join([ 76 | "__init__:", 77 | "two='ArgVal1'", 78 | "three='ArgVal2'", 79 | "four='ArgVal3'", 80 | ])) 81 | 82 | def test_q_argument_order_attributes1(self): 83 | import q 84 | q.writer.color = False 85 | 86 | class A: 87 | def __init__(self, two, three, four): 88 | self.attrib1 = 'Attrib1' 89 | self.attrib2 = 'Attrib2' 90 | q(self.attrib1, self.attrib2) 91 | 92 | A("ArgVal1", "ArgVal2", "ArgVal3") 93 | self.assertInQLog(".*".join([ 94 | "__init__:", 95 | "self.attrib1='Attrib1',", 96 | "self.attrib2='Attrib2'", 97 | ])) 98 | 99 | def test_q_argument_order_attributes2(self): 100 | import q 101 | q.writer.color = False 102 | 103 | class A: 104 | def __init__(s, two, three, four): 105 | s.attrib1 = 'Attrib1' 106 | s.attrib2 = 'Attrib2' 107 | q(s.attrib1, s.attrib2) 108 | 109 | A("ArgVal1", "ArgVal2", "ArgVal3") 110 | self.assertInQLog(".*".join([ 111 | "__init__:", 112 | "s.attrib1='Attrib1',", 113 | "s.attrib2='Attrib2'", 114 | ])) 115 | 116 | @unittest.skipIf(sys.version_info < (3, 8), "requires Python 3.8+") 117 | def test_q_multiple_calls_on_line(self): 118 | import q 119 | q.writer.color = False 120 | 121 | class A: 122 | def __init__(self, two, three, four): 123 | self.attrib1 = 'Attrib1' 124 | self.attrib2 = 'Attrib2' 125 | q(q(two, self.attrib1) + q(three, self.attrib2), four) 126 | 127 | A("ArgVal1", "ArgVal2", "ArgVal3") 128 | self.assertInQLog(".*".join([ 129 | "__init__:", 130 | "two='ArgVal1',", 131 | "self.attrib1='Attrib1'", 132 | "__init__:", 133 | "three='ArgVal2',", 134 | "self.attrib2='Attrib2'", 135 | "__init__:", 136 | # `q(two, self.attrib1) + q(three, self.attrib2)='ArgVal1ArgVal2',` 137 | # does not work despite that text being in the log, so just test 138 | # for `'ArgVal1ArgVal2',` 139 | "'ArgVal1ArgVal2',", 140 | "four='ArgVal3'", 141 | ])) 142 | 143 | def test_q_argument_order_attributes_and_arguments(self): 144 | import q 145 | q.writer.color = False 146 | 147 | class A: 148 | def __init__(self, two, three, four): 149 | self.attrib1 = 'Attrib1' 150 | self.attrib2 = 'Attrib2' 151 | q(two, three, self.attrib1, four, self.attrib2) 152 | 153 | A("ArgVal1", "ArgVal2", "ArgVal3") 154 | self.assertInQLog(".*".join([ 155 | "__init__:", 156 | "two='ArgVal1'", 157 | "three='ArgVal2'", 158 | "self.attrib1='Attrib1'", 159 | "four='ArgVal3'", 160 | "self.attrib2='Attrib2'", 161 | ])) 162 | 163 | def test_q_trace(self): 164 | import q 165 | q.writer.color = False 166 | 167 | @q 168 | def log1(msg='default'): 169 | return msg 170 | 171 | @q.t 172 | def log2(msg='default'): 173 | return msg 174 | 175 | log1('log1 message') 176 | log2('log2 message') 177 | 178 | self.assertInQLog("log1\\('log1 message'\\)") 179 | self.assertInQLog("log2\\('log2 message'\\)") 180 | 181 | def test_q_nested_bad_wrapper(self): 182 | # See http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem # noqa 183 | import q 184 | q.writer.color = False 185 | 186 | def wrapper(func): 187 | def do_nothing(*args, **kwargs): 188 | return func(*args, **kwargs) 189 | return do_nothing 190 | 191 | @wrapper 192 | @q 193 | @wrapper 194 | def decorated_log_bad(msg='default'): 195 | return msg 196 | 197 | decorated_log_bad('decorated bad message') 198 | self.assertInQLog(r"do_nothing\((?:\n\s*)?'" 199 | r"decorated bad message'\)") 200 | self.assertInQLog("-> 'decorated bad message'") 201 | 202 | def test_q_nested_good_wrappers(self): 203 | import q 204 | q.writer.color = False 205 | 206 | import functools 207 | 208 | def wrapper(func): 209 | def do_nothing(*args, **kwargs): 210 | return func(*args, **kwargs) 211 | return functools.update_wrapper(do_nothing, func) 212 | 213 | @wrapper 214 | @q 215 | @wrapper 216 | def decorated_log_good(msg='default'): 217 | return msg 218 | 219 | decorated_log_good('decorated good message') 220 | self.assertInQLog(r"decorated_log_good\((?:\n\s*)?'" 221 | r"decorated good message'\)") 222 | self.assertInQLog("-> 'decorated good message'") 223 | 224 | @unittest.skipIf(sys.version_info < (3, 3), "requires Python 3.3+") 225 | def test_q_trace_method(self): 226 | import q 227 | q.writer.color = False 228 | 229 | class A(object): 230 | @q 231 | def run1(self, arg): 232 | return arg 233 | 234 | @staticmethod 235 | @q 236 | def run2(arg): 237 | return arg 238 | 239 | @classmethod 240 | @q 241 | def run3(cls, arg): 242 | return arg 243 | 244 | a = A() 245 | a.run1('first message') 246 | A.run2('second message') 247 | A.run3('third message') 248 | 249 | self.assertInQLog(".*".join([ 250 | "\\bA.run1\\(", 251 | "'first message'\\)", 252 | ])) 253 | self.assertInQLog("-> 'first message'") 254 | 255 | self.assertInQLog(".*".join([ 256 | "\\bA.run2\\(", 257 | "'second message'\\)", 258 | ])) 259 | self.assertInQLog("-> 'second message'") 260 | 261 | self.assertInQLog(".*".join([ 262 | "\\bA.run3\\(", 263 | "'third message'\\)", 264 | ])) 265 | self.assertInQLog("-> 'third message'") 266 | 267 | 268 | unittest.main() 269 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /q.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Google Inc. All Rights Reserved. 2 | # vim: set ts=4 sw=4 et sts=4 ai: 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 | # use this file except in compliance with the License. You may obtain a copy 6 | # of the License at: http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software distrib- 9 | # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | # OR CONDITIONS OF ANY KIND, either express or implied. See the License for 11 | # specific language governing permissions and limitations under the License. 12 | 13 | """Quick and dirty debugging output for tired programmers. 14 | 15 | All output goes to /tmp/q, which you can watch with this shell command: 16 | 17 | tail -f /tmp/q 18 | 19 | To print the value of foo, insert this into your program: 20 | 21 | import q; q(foo) 22 | 23 | To print the value of something in the middle of an expression, insert 24 | "q()", "q/", or "q|". For example, given this statement: 25 | 26 | file.write(prefix + (sep or '').join(items)) 27 | 28 | ...you can print out various values without using any temporary variables: 29 | 30 | file.write(prefix + q(sep or '').join(items)) # prints (sep or '') 31 | file.write(q/prefix + (sep or '').join(items)) # prints prefix 32 | file.write(q|prefix + (sep or '').join(items)) # prints the arg to write 33 | 34 | To trace a function's arguments and return value, insert this above the def: 35 | 36 | import q 37 | @q 38 | 39 | To start an interactive console at any point in your code, call q.d(): 40 | 41 | import q; q.d() 42 | """ 43 | 44 | from __future__ import print_function 45 | 46 | import sys 47 | 48 | __author__ = 'Ka-Ping Yee ' 49 | 50 | # WARNING: Horrible abuse of sys.modules, __call__, __div__, __or__, inspect, 51 | # sys._getframe, and more! q's behaviour changes depending on the text of the 52 | # source code near its call site. Don't ever do this in real code! 53 | 54 | # These are reused below in both Q and Writer. 55 | ESCAPE_SEQUENCES = ['\x1b[0m'] + ['\x1b[3%dm' % i for i in range(1, 7)] 56 | 57 | if sys.version_info >= (3,): 58 | BASESTRING_TYPES = (str, bytes) 59 | TEXT_TYPES = (str,) 60 | else: 61 | BASESTRING_TYPES = (basestring,) # noqa 62 | TEXT_TYPES = (unicode,) # noqa 63 | 64 | 65 | # When we insert Q() into sys.modules, all the globals become None, so we 66 | # have to keep everything we use inside the Q class. 67 | class Q(object): 68 | __doc__ = __doc__ # from the module's __doc__ above 69 | 70 | import ast 71 | import code 72 | import dis 73 | import functools 74 | import inspect 75 | import os 76 | import pydoc 77 | import random 78 | import re 79 | import sys 80 | import tempfile 81 | import time 82 | 83 | # The debugging log will go to this file on Unix systems; 84 | # The debugging log will go to this fixed path on Unix systems. 85 | # Temporary files will be named with this prefix plus a random suffix. 86 | OUTPUT_PATH = '/tmp/q' 87 | 88 | NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES 89 | TEXT_REPR = pydoc.TextRepr() 90 | q_max_length = 1000000 91 | 92 | @property 93 | def short(self): 94 | cls = self.__class__ 95 | cls.TEXT_REPR = cls.pydoc.TextRepr() 96 | 97 | @property 98 | def long(self): 99 | cls = self.__class__ 100 | cls.TEXT_REPR = cls.pydoc.TextRepr() 101 | cls.TEXT_REPR.maxarray = cls.q_max_length 102 | cls.TEXT_REPR.maxdeque = cls.q_max_length 103 | cls.TEXT_REPR.maxdict = cls.q_max_length 104 | cls.TEXT_REPR.maxfrozenset = cls.q_max_length 105 | cls.TEXT_REPR.maxlevel = cls.q_max_length 106 | cls.TEXT_REPR.maxlist = cls.q_max_length 107 | cls.TEXT_REPR.maxlong = cls.q_max_length 108 | cls.TEXT_REPR.maxother = cls.q_max_length 109 | cls.TEXT_REPR.maxset = cls.q_max_length 110 | cls.TEXT_REPR.maxstring = cls.q_max_length 111 | cls.TEXT_REPR.maxtuple = cls.q_max_length 112 | 113 | @long.setter 114 | def long(self, value): 115 | cls = self.__class__ 116 | cls.q_max_length = value 117 | self.long 118 | 119 | # For portably converting strings between python2 and python3 120 | BASESTRING_TYPES = BASESTRING_TYPES 121 | TEXT_TYPES = TEXT_TYPES 122 | 123 | class FileWriter(object): 124 | """An object that appends to or overwrites a single file.""" 125 | import sys 126 | 127 | # For portably converting strings between python2 and python3 128 | BASESTRING_TYPES = BASESTRING_TYPES 129 | TEXT_TYPES = TEXT_TYPES 130 | 131 | def __init__(self, path): 132 | self.path = path 133 | self.open = open 134 | # App Engine's dev_appserver patches 'open' to simulate security 135 | # restrictions in production; we circumvent this to write output. 136 | if open.__name__ == 'FakeFile': # dev_appserver's patched 'file' 137 | self.open = open.__bases__[0] # the original built-in 'file' 138 | 139 | def write(self, mode, content): 140 | if 'b' not in mode: 141 | mode = '%sb' % mode 142 | if (isinstance(content, self.BASESTRING_TYPES) and 143 | isinstance(content, self.TEXT_TYPES)): 144 | content = content.encode('utf-8') 145 | try: 146 | f = self.open(self.path, mode) 147 | f.write(content) 148 | f.close() 149 | except IOError: 150 | pass 151 | 152 | class Writer: 153 | """Abstract away the output pipe, timestamping, and color support.""" 154 | 155 | NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES 156 | 157 | def __init__(self, file_writer, time): 158 | self.color = True 159 | self.file_writer = file_writer 160 | self.gap_seconds = 2 161 | self.time = time # the 'time' module (needed because no globals) 162 | self.start_time = self.time.time() 163 | self.last_write = 0 164 | 165 | def write(self, chunks): 166 | """Writes out a list of strings as a single timestamped unit.""" 167 | if not self.color: 168 | chunks = [x for x in chunks if not x.startswith('\x1b')] 169 | content = ''.join(chunks) 170 | 171 | now = self.time.time() 172 | prefix = '%4.1fs ' % ((now - self.start_time) % 100) 173 | indent = ' ' * len(prefix) 174 | if self.color: 175 | prefix = self.YELLOW + prefix + self.NORMAL 176 | if now - self.last_write >= self.gap_seconds: 177 | prefix = '\n' + prefix 178 | self.last_write = now 179 | 180 | output = prefix + content.replace('\n', '\n' + indent) 181 | self.file_writer.write('a', output + '\n') 182 | 183 | class Stanza: 184 | """Abstract away indentation and line-wrapping.""" 185 | 186 | def __init__(self, indent=0, width=80 - 7): 187 | self.chunks = [' ' * indent] 188 | self.indent = indent 189 | self.column = indent 190 | self.width = width 191 | 192 | def newline(self): 193 | if len(self.chunks) > 1: 194 | self.column = self.width 195 | 196 | def add(self, items, sep='', wrap=True): 197 | """Adds a list of strings that are to be printed on one line.""" 198 | items = list(map(str, items)) 199 | size = sum([len(x) for x in items if not x.startswith('\x1b')]) 200 | if (wrap and self.column > self.indent and 201 | self.column + len(sep) + size > self.width): 202 | self.chunks.append(sep.rstrip() + '\n' + ' ' * self.indent) 203 | self.column = self.indent 204 | else: 205 | self.chunks.append(sep) 206 | self.column += len(sep) 207 | self.chunks.extend(items) 208 | self.column += size 209 | 210 | def __init__(self): 211 | self.writer = self.Writer(self.FileWriter(self.OUTPUT_PATH), self.time) 212 | self.indent = 0 213 | # in_console tracks whether we're in an interactive console. 214 | # We use it to display the caller as "" instead of "". 215 | self.in_console = False 216 | 217 | def unindent(self, lines): 218 | """Removes any indentation that is common to all of the given lines.""" 219 | indent = min( 220 | len(self.re.match(r'^ *', line).group()) for line in lines) 221 | return [line[indent:].rstrip() for line in lines] 222 | 223 | def safe_repr(self, value): 224 | # TODO: Use colour to distinguish '...' elision from actual '...' 225 | # TODO: Show a nicer repr for SRE.Match objects. 226 | # TODO: Show a nicer repr for big multiline strings. 227 | result = self.TEXT_REPR.repr(value) 228 | if isinstance(value, self.BASESTRING_TYPES) and len(value) > 80: 229 | # If the string is big, save it to a file for later examination. 230 | if isinstance(value, self.TEXT_TYPES): 231 | value = value.encode('utf-8') 232 | path = self.OUTPUT_PATH + ( 233 | '%08d.txt' % self.random.randrange(100000000)) 234 | self.FileWriter(path).write('w', value) 235 | result += ' (file://' + path + ')' 236 | return result 237 | 238 | class CallVisitor(ast.NodeVisitor): 239 | def __init__(self, call_position): 240 | self.current_position = 0 241 | self.call_position = call_position 242 | self.call_node = None 243 | 244 | def visit_Call(self, node): 245 | # Arguments have a lower call position then the function call 246 | # For instance, in q(q(1) + q(2)), 247 | # q(1) has position 0, q(2) has position 1, 248 | # and q(q(1) + q(2)) has position 2 249 | for arg in node.args: 250 | self.visit(arg) 251 | 252 | if self.current_position == self.call_position: 253 | self.call_node = node 254 | 255 | self.current_position += 1 256 | 257 | def get_call_exprs(self, caller_frame, line): 258 | """Extracts argument expression labels from the source of a q() call using basic parsing.""" 259 | line = line.lstrip() 260 | try: 261 | tree = self.ast.parse(line) 262 | except SyntaxError: 263 | return None 264 | 265 | # Try accurate extraction on Python 3.8+, but always fallback to basic if it fails or returns nothing. 266 | raw = None 267 | if self.sys.version_info >= (3, 8): 268 | try: 269 | raw = self._get_accurate_call_exprs(caller_frame, line, tree) 270 | except Exception: 271 | raw = None 272 | if not raw: 273 | raw = self._get_basic_call_exprs(caller_frame, line, tree) 274 | if not raw: 275 | return None 276 | 277 | # Label simple arguments (names or attributes), leave others unlabeled 278 | labels = [] 279 | simple_re = self.re.compile(r'^[A-Za-z_][A-Za-z0-9_\.]*$') 280 | for expr in raw: 281 | expr = expr.strip() 282 | if simple_re.match(expr): 283 | labels.append(expr) 284 | else: 285 | labels.append(None) 286 | return labels 287 | 288 | def _get_basic_call_exprs(self, caller_frame, line, tree): 289 | """Gets the argument expressions from the source of a function call. 290 | 291 | Slightly buggy (multiple calls to q() on a single line cause garbled 292 | output, #67), but works on all Python versions. 293 | """ 294 | for node in self.ast.walk(tree): 295 | if isinstance(node, self.ast.Call): 296 | offsets = [] 297 | for arg in node.args: 298 | # In Python 3.4 the col_offset is calculated wrong. See 299 | # https://bugs.python.org/issue21295 300 | if isinstance(arg, self.ast.Attribute) and ( 301 | (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)): 302 | offsets.append(arg.col_offset - len(arg.value.id) - 1) 303 | else: 304 | offsets.append(arg.col_offset) 305 | if node.keywords: 306 | line = line[:node.keywords[0].value.col_offset] 307 | line = self.re.sub(r'\w+\s*=\s*$', '', line) 308 | else: 309 | line = self.re.sub(r'\s*\)\s*$', '', line) 310 | offsets.append(len(line)) 311 | args = [] 312 | for i in range(len(node.args)): 313 | args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) 314 | return args 315 | 316 | def _get_accurate_call_exprs(self, caller_frame, line, tree): 317 | """Gets the argument expressions from the source of a function call. 318 | 319 | Accurate, but depends on Python 3.8+. 320 | """ 321 | # There can be multiple function calls on a line 322 | # (for example: q(1) + q(2)), so in order to show 323 | # correct output, we need to identify what function call we 324 | # are getting the call expressions for. To do this, we can 325 | # use frame data to get the caller's bytecode and the 326 | # bytecode instruction being executed. We can then 327 | # count the number of CALL_* opcodes before the condition 328 | # `instruction.starts_line is not None` is met. 329 | caller_bytecode = caller_frame.f_code 330 | call_bytecode_instruction_offset = caller_frame.f_lasti 331 | bytecode_instructions = \ 332 | tuple(self.dis.get_instructions(caller_bytecode)) 333 | call_bytecode_instruction_index = 0 334 | for instruction in bytecode_instructions: 335 | if instruction.offset == call_bytecode_instruction_offset: 336 | break 337 | elif instruction.offset > call_bytecode_instruction_offset: 338 | # It seems sometimes CACHE instructions cause 339 | # caller_frame.f_lasti to be after the call instruction offset 340 | call_bytecode_instruction_index -= 1 341 | break 342 | call_bytecode_instruction_index += 1 343 | 344 | current_bytecode_instruction = \ 345 | bytecode_instructions[call_bytecode_instruction_index] 346 | position_of_call_on_line = 0 347 | instruction_index = call_bytecode_instruction_index 348 | while current_bytecode_instruction.starts_line is None: 349 | instruction_index = instruction_index - 1 350 | current_bytecode_instruction = \ 351 | bytecode_instructions[instruction_index] 352 | if current_bytecode_instruction.opname.startswith('CALL'): 353 | position_of_call_on_line += 1 354 | 355 | call_visitor = self.CallVisitor(position_of_call_on_line) 356 | call_visitor.visit(tree) 357 | node = call_visitor.call_node 358 | 359 | offsets = [] 360 | for arg in node.args: 361 | offsets.append(arg.col_offset) 362 | if node.keywords: 363 | line = line[:node.keywords[0].value.col_offset] 364 | line = self.re.sub(r'\w+\s*=\s*$', '', line) 365 | else: 366 | line = self.re.sub(r'\s*\)\s*$', '', line) 367 | offsets.append(node.end_col_offset - 1) 368 | args = [] 369 | for i in range(len(node.args)): 370 | args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) 371 | return args 372 | 373 | def show(self, func_name, values, labels=None): 374 | """Prints out nice representations of the given values.""" 375 | s = self.Stanza(self.indent) 376 | if func_name == '' and self.in_console: 377 | func_name = '' 378 | s.add([func_name + ': ']) 379 | reprs = map(self.safe_repr, values) 380 | if labels: 381 | sep = '' 382 | for label, val_repr in zip(labels, reprs): 383 | if label: 384 | # Labelled argument 385 | s.add([label + '=', self.CYAN, val_repr, self.NORMAL], sep) 386 | else: 387 | # Unlabelled argument 388 | s.add([self.CYAN, val_repr, self.NORMAL], sep) 389 | sep = ', ' 390 | else: 391 | sep = '' 392 | for val_repr in reprs: 393 | s.add([self.CYAN, val_repr, self.NORMAL], sep) 394 | sep = ', ' 395 | self.writer.write(s.chunks) 396 | 397 | def trace(self, func): 398 | """Decorator to print out a function's arguments and return value.""" 399 | 400 | def get_func_name(func): 401 | return getattr(func, "__qualname__", func.__name__) 402 | 403 | def wrapper(*args, **kwargs): 404 | # Print out the call to the function with its arguments. 405 | s = self.Stanza(self.indent) 406 | s.add([self.GREEN, get_func_name(func), self.NORMAL, '(']) 407 | s.indent += 4 408 | sep = '' 409 | for arg in args: 410 | s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep) 411 | sep = ', ' 412 | for name, value in sorted(kwargs.items()): 413 | s.add([name + '=', self.CYAN, self.safe_repr(value), 414 | self.NORMAL], sep) 415 | sep = ', ' 416 | s.add(')', wrap=False) 417 | self.writer.write(s.chunks) 418 | 419 | # Call the function. 420 | self.indent += 2 421 | try: 422 | result = func(*args, **kwargs) 423 | except Exception: 424 | # Display an exception. 425 | self.indent -= 2 426 | etype, evalue, etb = self.sys.exc_info() 427 | info = self.inspect.getframeinfo(etb.tb_next, context=3) 428 | s = self.Stanza(self.indent) 429 | s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL]) 430 | s.add(['at ', info.filename, ':', info.lineno], ' ') 431 | lines = self.unindent(info.code_context) 432 | firstlineno = info.lineno - info.index 433 | fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd' 434 | for i, line in enumerate(lines): 435 | s.newline() 436 | s.add([ 437 | i == info.index and self.MAGENTA or '', 438 | fmt % (i + firstlineno), 439 | i == info.index and '> ' or ': ', line, self.NORMAL]) 440 | self.writer.write(s.chunks) 441 | raise 442 | 443 | # Display the return value. 444 | self.indent -= 2 445 | s = self.Stanza(self.indent) 446 | s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result), 447 | self.NORMAL]) 448 | self.writer.write(s.chunks) 449 | return result 450 | return self.functools.update_wrapper(wrapper, func) 451 | 452 | def __call__(self, *args): 453 | """If invoked as a decorator on a function, adds tracing output to the 454 | function; otherwise immediately prints out the arguments.""" 455 | caller_frame = self.sys._getframe(1) 456 | info = self.inspect.getframeinfo(caller_frame, context=9) 457 | 458 | # info.index is the index of the line containing the end of the call 459 | # expression, so this gets a few lines up to the end of the expression. 460 | lines = [''] 461 | if info.code_context: 462 | lines = info.code_context[:info.index + 1] 463 | 464 | # If we see "@q" on a single line, behave like a trace decorator. 465 | for line in lines: 466 | if line.strip() in ('@q', '@q()') and args: 467 | return self.trace(args[0]) 468 | 469 | # Otherwise, search for the beginning of the call expression; once it 470 | # parses, use the expressions in the call to label the debugging 471 | # output. 472 | for i in range(1, len(lines) + 1): 473 | labels = self.get_call_exprs(caller_frame, 474 | ''.join(lines[-i:]).replace('\n', '')) 475 | if labels: 476 | break 477 | self.show(info.function, args, labels) 478 | return args and args[0] 479 | 480 | def __truediv__(self, arg): # a tight-binding operator 481 | """Prints out and returns the argument.""" 482 | info = self.inspect.getframeinfo(self.sys._getframe(1)) 483 | self.show(info.function, [arg]) 484 | return arg 485 | # Compat for Python 2 without from future import __division__ turned on 486 | __div__ = __truediv__ 487 | 488 | __or__ = __div__ # a loose-binding operator 489 | q = __call__ # backward compatibility with @q.q 490 | t = trace # backward compatibility with @q.t 491 | __name__ = 'Q' # App Engine's import hook dies if this isn't present 492 | 493 | def d(self, depth=1): 494 | """Launches an interactive console at the point where it's called.""" 495 | info = self.inspect.getframeinfo(self.sys._getframe(1)) 496 | s = self.Stanza(self.indent) 497 | s.add([info.function + ': ']) 498 | s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL]) 499 | self.writer.write(s.chunks) 500 | 501 | frame = self.sys._getframe(depth) 502 | env = frame.f_globals.copy() 503 | env.update(frame.f_locals) 504 | self.indent += 2 505 | self.in_console = True 506 | self.code.interact( 507 | 'Python console opened by q.d() in ' + info.function, local=env) 508 | self.in_console = False 509 | self.indent -= 2 510 | 511 | s = self.Stanza(self.indent) 512 | s.add([info.function + ': ']) 513 | s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL]) 514 | self.writer.write(s.chunks) 515 | 516 | 517 | # Install the Q() object in sys.modules so that "import q" gives a callable q. 518 | q = Q() 519 | q.long 520 | sys.modules['q'] = q 521 | --------------------------------------------------------------------------------