├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CODESHELTER.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── q.py ├── setup.cfg ├── setup.py └── test └── test_basic.py /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | If TMPDIR is set, the output goes to $TMPDIR/q. 20 | 21 | To print the value of foo, insert this into your program: 22 | 23 | import q; q(foo) 24 | 25 | To print the value of something in the middle of an expression, insert 26 | "q()", "q/", or "q|". For example, given this statement: 27 | 28 | file.write(prefix + (sep or '').join(items)) 29 | 30 | ...you can print out various values without using any temporary variables: 31 | 32 | file.write(prefix + q(sep or '').join(items)) # prints (sep or '') 33 | file.write(q/prefix + (sep or '').join(items)) # prints prefix 34 | file.write(q|prefix + (sep or '').join(items)) # prints the arg to write 35 | 36 | To trace a function's arguments and return value, insert this above the def: 37 | 38 | import q 39 | @q 40 | 41 | To start an interactive console at any point in your code, call q.d(): 42 | 43 | import q; q.d() 44 | """ 45 | 46 | from __future__ import print_function 47 | 48 | import sys 49 | 50 | __author__ = 'Ka-Ping Yee ' 51 | 52 | # WARNING: Horrible abuse of sys.modules, __call__, __div__, __or__, inspect, 53 | # sys._getframe, and more! q's behaviour changes depending on the text of the 54 | # source code near its call site. Don't ever do this in real code! 55 | 56 | # These are reused below in both Q and Writer. 57 | ESCAPE_SEQUENCES = ['\x1b[0m'] + ['\x1b[3%dm' % i for i in range(1, 7)] 58 | 59 | if sys.version_info >= (3,): 60 | BASESTRING_TYPES = (str, bytes) 61 | TEXT_TYPES = (str,) 62 | else: 63 | BASESTRING_TYPES = (basestring,) # noqa 64 | TEXT_TYPES = (unicode,) # noqa 65 | 66 | 67 | # When we insert Q() into sys.modules, all the globals become None, so we 68 | # have to keep everything we use inside the Q class. 69 | class Q(object): 70 | __doc__ = __doc__ # from the module's __doc__ above 71 | 72 | import ast 73 | import code 74 | import dis 75 | import functools 76 | import inspect 77 | import os 78 | import pydoc 79 | import random 80 | import re 81 | import sys 82 | import tempfile 83 | import time 84 | 85 | # The debugging log will go to this file; temporary files will also have 86 | # this path as a prefix, followed by a random number. 87 | OUTPUT_PATH = os.path.join(tempfile.gettempdir(), 'q') 88 | 89 | NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES 90 | TEXT_REPR = pydoc.TextRepr() 91 | q_max_length = 1000000 92 | 93 | @property 94 | def short(self): 95 | cls = self.__class__ 96 | cls.TEXT_REPR = cls.pydoc.TextRepr() 97 | 98 | @property 99 | def long(self): 100 | cls = self.__class__ 101 | cls.TEXT_REPR = cls.pydoc.TextRepr() 102 | cls.TEXT_REPR.maxarray = cls.q_max_length 103 | cls.TEXT_REPR.maxdeque = cls.q_max_length 104 | cls.TEXT_REPR.maxdict = cls.q_max_length 105 | cls.TEXT_REPR.maxfrozenset = cls.q_max_length 106 | cls.TEXT_REPR.maxlevel = cls.q_max_length 107 | cls.TEXT_REPR.maxlist = cls.q_max_length 108 | cls.TEXT_REPR.maxlong = cls.q_max_length 109 | cls.TEXT_REPR.maxother = cls.q_max_length 110 | cls.TEXT_REPR.maxset = cls.q_max_length 111 | cls.TEXT_REPR.maxstring = cls.q_max_length 112 | cls.TEXT_REPR.maxtuple = cls.q_max_length 113 | 114 | @long.setter 115 | def long(self, value): 116 | cls = self.__class__ 117 | cls.q_max_length = value 118 | self.long 119 | 120 | # For portably converting strings between python2 and python3 121 | BASESTRING_TYPES = BASESTRING_TYPES 122 | TEXT_TYPES = TEXT_TYPES 123 | 124 | class FileWriter(object): 125 | """An object that appends to or overwrites a single file.""" 126 | import sys 127 | 128 | # For portably converting strings between python2 and python3 129 | BASESTRING_TYPES = BASESTRING_TYPES 130 | TEXT_TYPES = TEXT_TYPES 131 | 132 | def __init__(self, path): 133 | self.path = path 134 | self.open = open 135 | # App Engine's dev_appserver patches 'open' to simulate security 136 | # restrictions in production; we circumvent this to write output. 137 | if open.__name__ == 'FakeFile': # dev_appserver's patched 'file' 138 | self.open = open.__bases__[0] # the original built-in 'file' 139 | 140 | def write(self, mode, content): 141 | if 'b' not in mode: 142 | mode = '%sb' % mode 143 | if (isinstance(content, self.BASESTRING_TYPES) and 144 | isinstance(content, self.TEXT_TYPES)): 145 | content = content.encode('utf-8') 146 | try: 147 | f = self.open(self.path, mode) 148 | f.write(content) 149 | f.close() 150 | except IOError: 151 | pass 152 | 153 | class Writer: 154 | """Abstract away the output pipe, timestamping, and color support.""" 155 | 156 | NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES 157 | 158 | def __init__(self, file_writer, time): 159 | self.color = True 160 | self.file_writer = file_writer 161 | self.gap_seconds = 2 162 | self.time = time # the 'time' module (needed because no globals) 163 | self.start_time = self.time.time() 164 | self.last_write = 0 165 | 166 | def write(self, chunks): 167 | """Writes out a list of strings as a single timestamped unit.""" 168 | if not self.color: 169 | chunks = [x for x in chunks if not x.startswith('\x1b')] 170 | content = ''.join(chunks) 171 | 172 | now = self.time.time() 173 | prefix = '%4.1fs ' % ((now - self.start_time) % 100) 174 | indent = ' ' * len(prefix) 175 | if self.color: 176 | prefix = self.YELLOW + prefix + self.NORMAL 177 | if now - self.last_write >= self.gap_seconds: 178 | prefix = '\n' + prefix 179 | self.last_write = now 180 | 181 | output = prefix + content.replace('\n', '\n' + indent) 182 | self.file_writer.write('a', output + '\n') 183 | 184 | class Stanza: 185 | """Abstract away indentation and line-wrapping.""" 186 | 187 | def __init__(self, indent=0, width=80 - 7): 188 | self.chunks = [' ' * indent] 189 | self.indent = indent 190 | self.column = indent 191 | self.width = width 192 | 193 | def newline(self): 194 | if len(self.chunks) > 1: 195 | self.column = self.width 196 | 197 | def add(self, items, sep='', wrap=True): 198 | """Adds a list of strings that are to be printed on one line.""" 199 | items = list(map(str, items)) 200 | size = sum([len(x) for x in items if not x.startswith('\x1b')]) 201 | if (wrap and self.column > self.indent and 202 | self.column + len(sep) + size > self.width): 203 | self.chunks.append(sep.rstrip() + '\n' + ' ' * self.indent) 204 | self.column = self.indent 205 | else: 206 | self.chunks.append(sep) 207 | self.column += len(sep) 208 | self.chunks.extend(items) 209 | self.column += size 210 | 211 | def __init__(self): 212 | self.writer = self.Writer(self.FileWriter(self.OUTPUT_PATH), self.time) 213 | self.indent = 0 214 | # in_console tracks whether we're in an interactive console. 215 | # We use it to display the caller as "" instead of "". 216 | self.in_console = False 217 | 218 | def unindent(self, lines): 219 | """Removes any indentation that is common to all of the given lines.""" 220 | indent = min( 221 | len(self.re.match(r'^ *', line).group()) for line in lines) 222 | return [line[indent:].rstrip() for line in lines] 223 | 224 | def safe_repr(self, value): 225 | # TODO: Use colour to distinguish '...' elision from actual '...' 226 | # TODO: Show a nicer repr for SRE.Match objects. 227 | # TODO: Show a nicer repr for big multiline strings. 228 | result = self.TEXT_REPR.repr(value) 229 | if isinstance(value, self.BASESTRING_TYPES) and len(value) > 80: 230 | # If the string is big, save it to a file for later examination. 231 | if isinstance(value, self.TEXT_TYPES): 232 | value = value.encode('utf-8') 233 | path = self.OUTPUT_PATH + ( 234 | '%08d.txt' % self.random.randrange(100000000)) 235 | self.FileWriter(path).write('w', value) 236 | result += ' (file://' + path + ')' 237 | return result 238 | 239 | class CallVisitor(ast.NodeVisitor): 240 | def __init__(self, call_position): 241 | self.current_position = 0 242 | self.call_position = call_position 243 | self.call_node = None 244 | 245 | def visit_Call(self, node): 246 | # Arguments have a lower call position then the function call 247 | # For instance, in q(q(1) + q(2)), 248 | # q(1) has position 0, q(2) has position 1, 249 | # and q(q(1) + q(2)) has position 2 250 | for arg in node.args: 251 | self.visit(arg) 252 | 253 | if self.current_position == self.call_position: 254 | self.call_node = node 255 | 256 | self.current_position += 1 257 | 258 | def get_call_exprs(self, caller_frame, line): 259 | """Gets the argument expressions from the source of a function call.""" 260 | line = line.lstrip() 261 | try: 262 | tree = self.ast.parse(line) 263 | except SyntaxError: 264 | return None 265 | 266 | if self.sys.version_info >= (3, 8): 267 | return self._get_accurate_call_exprs(caller_frame, line, tree) 268 | 269 | return self._get_basic_call_exprs(caller_frame, line, tree) 270 | 271 | def _get_basic_call_exprs(self, caller_frame, line, tree): 272 | """Gets the argument expressions from the source of a function call. 273 | 274 | Slightly buggy (multiple calls to q() on a single line cause garbled 275 | output, #67), but works on all Python versions. 276 | """ 277 | for node in self.ast.walk(tree): 278 | if isinstance(node, self.ast.Call): 279 | offsets = [] 280 | for arg in node.args: 281 | # In Python 3.4 the col_offset is calculated wrong. See 282 | # https://bugs.python.org/issue21295 283 | if isinstance(arg, self.ast.Attribute) and ( 284 | (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)): 285 | offsets.append(arg.col_offset - len(arg.value.id) - 1) 286 | else: 287 | offsets.append(arg.col_offset) 288 | if node.keywords: 289 | line = line[:node.keywords[0].value.col_offset] 290 | line = self.re.sub(r'\w+\s*=\s*$', '', line) 291 | else: 292 | line = self.re.sub(r'\s*\)\s*$', '', line) 293 | offsets.append(len(line)) 294 | args = [] 295 | for i in range(len(node.args)): 296 | args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) 297 | return args 298 | 299 | def _get_accurate_call_exprs(self, caller_frame, line, tree): 300 | """Gets the argument expressions from the source of a function call. 301 | 302 | Accurate, but depends on Python 3.8+. 303 | """ 304 | # There can be multiple function calls on a line 305 | # (for example: q(1) + q(2)), so in order to show 306 | # correct output, we need to identify what function call we 307 | # are getting the call expressions for. To do this, we can 308 | # use frame data to get the caller's bytecode and the 309 | # bytecode instruction being executed. We can then 310 | # count the number of CALL_* opcodes before the condition 311 | # `instruction.starts_line is not None` is met. 312 | caller_bytecode = caller_frame.f_code 313 | call_bytecode_instruction_offset = caller_frame.f_lasti 314 | bytecode_instructions = \ 315 | tuple(self.dis.get_instructions(caller_bytecode)) 316 | call_bytecode_instruction_index = 0 317 | for instruction in bytecode_instructions: 318 | if instruction.offset == call_bytecode_instruction_offset: 319 | break 320 | elif instruction.offset > call_bytecode_instruction_offset: 321 | # It seems sometimes CACHE instructions cause 322 | # caller_frame.f_lasti to be after the call instruction offset 323 | call_bytecode_instruction_index -= 1 324 | break 325 | call_bytecode_instruction_index += 1 326 | 327 | current_bytecode_instruction = \ 328 | bytecode_instructions[call_bytecode_instruction_index] 329 | position_of_call_on_line = 0 330 | instruction_index = call_bytecode_instruction_index 331 | while current_bytecode_instruction.starts_line is None: 332 | instruction_index = instruction_index - 1 333 | current_bytecode_instruction = \ 334 | bytecode_instructions[instruction_index] 335 | if current_bytecode_instruction.opname.startswith('CALL'): 336 | position_of_call_on_line += 1 337 | 338 | call_visitor = self.CallVisitor(position_of_call_on_line) 339 | call_visitor.visit(tree) 340 | node = call_visitor.call_node 341 | 342 | offsets = [] 343 | for arg in node.args: 344 | offsets.append(arg.col_offset) 345 | if node.keywords: 346 | line = line[:node.keywords[0].value.col_offset] 347 | line = self.re.sub(r'\w+\s*=\s*$', '', line) 348 | else: 349 | line = self.re.sub(r'\s*\)\s*$', '', line) 350 | offsets.append(node.end_col_offset - 1) 351 | args = [] 352 | for i in range(len(node.args)): 353 | args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) 354 | return args 355 | 356 | def show(self, func_name, values, labels=None): 357 | """Prints out nice representations of the given values.""" 358 | s = self.Stanza(self.indent) 359 | if func_name == '' and self.in_console: 360 | func_name = '' 361 | s.add([func_name + ': ']) 362 | reprs = map(self.safe_repr, values) 363 | if labels: 364 | sep = '' 365 | for label, repr in zip(labels, reprs): 366 | s.add([label + '=', self.CYAN, repr, self.NORMAL], sep) 367 | sep = ', ' 368 | else: 369 | sep = '' 370 | for repr in reprs: 371 | s.add([self.CYAN, repr, self.NORMAL], sep) 372 | sep = ', ' 373 | self.writer.write(s.chunks) 374 | 375 | def trace(self, func): 376 | """Decorator to print out a function's arguments and return value.""" 377 | 378 | def get_func_name(func): 379 | return getattr(func, "__qualname__", func.__name__) 380 | 381 | def wrapper(*args, **kwargs): 382 | # Print out the call to the function with its arguments. 383 | s = self.Stanza(self.indent) 384 | s.add([self.GREEN, get_func_name(func), self.NORMAL, '(']) 385 | s.indent += 4 386 | sep = '' 387 | for arg in args: 388 | s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep) 389 | sep = ', ' 390 | for name, value in sorted(kwargs.items()): 391 | s.add([name + '=', self.CYAN, self.safe_repr(value), 392 | self.NORMAL], sep) 393 | sep = ', ' 394 | s.add(')', wrap=False) 395 | self.writer.write(s.chunks) 396 | 397 | # Call the function. 398 | self.indent += 2 399 | try: 400 | result = func(*args, **kwargs) 401 | except Exception: 402 | # Display an exception. 403 | self.indent -= 2 404 | etype, evalue, etb = self.sys.exc_info() 405 | info = self.inspect.getframeinfo(etb.tb_next, context=3) 406 | s = self.Stanza(self.indent) 407 | s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL]) 408 | s.add(['at ', info.filename, ':', info.lineno], ' ') 409 | lines = self.unindent(info.code_context) 410 | firstlineno = info.lineno - info.index 411 | fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd' 412 | for i, line in enumerate(lines): 413 | s.newline() 414 | s.add([ 415 | i == info.index and self.MAGENTA or '', 416 | fmt % (i + firstlineno), 417 | i == info.index and '> ' or ': ', line, self.NORMAL]) 418 | self.writer.write(s.chunks) 419 | raise 420 | 421 | # Display the return value. 422 | self.indent -= 2 423 | s = self.Stanza(self.indent) 424 | s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result), 425 | self.NORMAL]) 426 | self.writer.write(s.chunks) 427 | return result 428 | return self.functools.update_wrapper(wrapper, func) 429 | 430 | def __call__(self, *args): 431 | """If invoked as a decorator on a function, adds tracing output to the 432 | function; otherwise immediately prints out the arguments.""" 433 | caller_frame = self.sys._getframe(1) 434 | info = self.inspect.getframeinfo(caller_frame, context=9) 435 | 436 | # info.index is the index of the line containing the end of the call 437 | # expression, so this gets a few lines up to the end of the expression. 438 | lines = [''] 439 | if info.code_context: 440 | lines = info.code_context[:info.index + 1] 441 | 442 | # If we see "@q" on a single line, behave like a trace decorator. 443 | for line in lines: 444 | if line.strip() in ('@q', '@q()') and args: 445 | return self.trace(args[0]) 446 | 447 | # Otherwise, search for the beginning of the call expression; once it 448 | # parses, use the expressions in the call to label the debugging 449 | # output. 450 | for i in range(1, len(lines) + 1): 451 | labels = self.get_call_exprs(caller_frame, 452 | ''.join(lines[-i:]).replace('\n', '')) 453 | if labels: 454 | break 455 | self.show(info.function, args, labels) 456 | return args and args[0] 457 | 458 | def __truediv__(self, arg): # a tight-binding operator 459 | """Prints out and returns the argument.""" 460 | info = self.inspect.getframeinfo(self.sys._getframe(1)) 461 | self.show(info.function, [arg]) 462 | return arg 463 | # Compat for Python 2 without from future import __division__ turned on 464 | __div__ = __truediv__ 465 | 466 | __or__ = __div__ # a loose-binding operator 467 | q = __call__ # backward compatibility with @q.q 468 | t = trace # backward compatibility with @q.t 469 | __name__ = 'Q' # App Engine's import hook dies if this isn't present 470 | 471 | def d(self, depth=1): 472 | """Launches an interactive console at the point where it's called.""" 473 | info = self.inspect.getframeinfo(self.sys._getframe(1)) 474 | s = self.Stanza(self.indent) 475 | s.add([info.function + ': ']) 476 | s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL]) 477 | self.writer.write(s.chunks) 478 | 479 | frame = self.sys._getframe(depth) 480 | env = frame.f_globals.copy() 481 | env.update(frame.f_locals) 482 | self.indent += 2 483 | self.in_console = True 484 | self.code.interact( 485 | 'Python console opened by q.d() in ' + info.function, local=env) 486 | self.in_console = False 487 | self.indent -= 2 488 | 489 | s = self.Stanza(self.indent) 490 | s.add([info.function + ': ']) 491 | s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL]) 492 | self.writer.write(s.chunks) 493 | 494 | 495 | # Install the Q() object in sys.modules so that "import q" gives a callable q. 496 | q = Q() 497 | q.long 498 | sys.modules['q'] = q 499 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | [bdist_wheel] 4 | universal=1 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 15 | 16 | class TestQBasic(unittest.TestCase): 17 | 18 | def setUp(self): 19 | if os.path.exists('/tmp/q'): 20 | os.remove('/tmp/q') 21 | 22 | def tearDown(self): 23 | self.setUp() 24 | 25 | def assertInQLog(self, string): 26 | # Check the log file exists. 27 | self.assertTrue(os.path.exists('/tmp/q')) 28 | 29 | # Read in the data. 30 | f = open('/tmp/q', 'r') 31 | logdata = f.read() 32 | f.close() 33 | 34 | # Check the string is found in the log file. 35 | # We can't use self.assertRegexpMatches as we need re.DOTALL 36 | expected_regexp = re.compile('.*%s.*' % string, re.DOTALL) 37 | if not expected_regexp.search(logdata): 38 | msg = '%s: %r not found in\n%s\n%s\n%s' % ( 39 | "Regexp didn't match", 40 | expected_regexp.pattern, 41 | "-"*75, 42 | logdata, 43 | "-"*75, 44 | ) 45 | raise self.failureException(msg) 46 | 47 | def test_q_log_message(self): 48 | import q 49 | q.q('Test message') 50 | self.assertInQLog('Test message') 51 | 52 | def test_q_function_call(self): 53 | import q 54 | 55 | @q.t 56 | def test(arg): 57 | return 'RetVal' 58 | 59 | self.assertEqual('RetVal', test('ArgVal')) 60 | 61 | self.assertInQLog('ArgVal') 62 | self.assertInQLog('RetVal') 63 | 64 | def test_q_argument_order_arguments(self): 65 | import q 66 | q.writer.color = False 67 | 68 | class A: 69 | def __init__(self, two, three, four): 70 | q(two, three, four) 71 | 72 | A("ArgVal1", "ArgVal2", "ArgVal3") 73 | self.assertInQLog(".*".join([ 74 | "__init__:", 75 | "two='ArgVal1'", 76 | "three='ArgVal2'", 77 | "four='ArgVal3'", 78 | ])) 79 | 80 | def test_q_argument_order_attributes1(self): 81 | import q 82 | q.writer.color = False 83 | 84 | class A: 85 | def __init__(self, two, three, four): 86 | self.attrib1 = 'Attrib1' 87 | self.attrib2 = 'Attrib2' 88 | q(self.attrib1, self.attrib2) 89 | 90 | A("ArgVal1", "ArgVal2", "ArgVal3") 91 | self.assertInQLog(".*".join([ 92 | "__init__:", 93 | "self.attrib1='Attrib1',", 94 | "self.attrib2='Attrib2'", 95 | ])) 96 | 97 | def test_q_argument_order_attributes2(self): 98 | import q 99 | q.writer.color = False 100 | 101 | class A: 102 | def __init__(s, two, three, four): 103 | s.attrib1 = 'Attrib1' 104 | s.attrib2 = 'Attrib2' 105 | q(s.attrib1, s.attrib2) 106 | 107 | A("ArgVal1", "ArgVal2", "ArgVal3") 108 | self.assertInQLog(".*".join([ 109 | "__init__:", 110 | "s.attrib1='Attrib1',", 111 | "s.attrib2='Attrib2'", 112 | ])) 113 | 114 | @unittest.skipIf(sys.version_info < (3, 8), "requires Python 3.8+") 115 | def test_q_multiple_calls_on_line(self): 116 | import q 117 | q.writer.color = False 118 | 119 | class A: 120 | def __init__(self, two, three, four): 121 | self.attrib1 = 'Attrib1' 122 | self.attrib2 = 'Attrib2' 123 | q(q(two, self.attrib1) + q(three, self.attrib2), four) 124 | 125 | A("ArgVal1", "ArgVal2", "ArgVal3") 126 | self.assertInQLog(".*".join([ 127 | "__init__:", 128 | "two='ArgVal1',", 129 | "self.attrib1='Attrib1'", 130 | "__init__:", 131 | "three='ArgVal2',", 132 | "self.attrib2='Attrib2'", 133 | "__init__:", 134 | # `q(two, self.attrib1) + q(three, self.attrib2)='ArgVal1ArgVal2',` 135 | # does not work despite that text being in the log, so just test 136 | # for `'ArgVal1ArgVal2',` 137 | "'ArgVal1ArgVal2',", 138 | "four='ArgVal3'", 139 | ])) 140 | 141 | def test_q_argument_order_attributes_and_arguments(self): 142 | import q 143 | q.writer.color = False 144 | 145 | class A: 146 | def __init__(self, two, three, four): 147 | self.attrib1 = 'Attrib1' 148 | self.attrib2 = 'Attrib2' 149 | q(two, three, self.attrib1, four, self.attrib2) 150 | 151 | A("ArgVal1", "ArgVal2", "ArgVal3") 152 | self.assertInQLog(".*".join([ 153 | "__init__:", 154 | "two='ArgVal1'", 155 | "three='ArgVal2'", 156 | "self.attrib1='Attrib1'", 157 | "four='ArgVal3'", 158 | "self.attrib2='Attrib2'", 159 | ])) 160 | 161 | def test_q_trace(self): 162 | import q 163 | q.writer.color = False 164 | 165 | @q 166 | def log1(msg='default'): 167 | return msg 168 | 169 | @q.t 170 | def log2(msg='default'): 171 | return msg 172 | 173 | log1('log1 message') 174 | log2('log2 message') 175 | 176 | self.assertInQLog("log1\\('log1 message'\\)") 177 | self.assertInQLog("log2\\('log2 message'\\)") 178 | 179 | def test_q_nested_bad_wrapper(self): 180 | # See http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem # noqa 181 | import q 182 | q.writer.color = False 183 | 184 | def wrapper(func): 185 | def do_nothing(*args, **kwargs): 186 | return func(*args, **kwargs) 187 | return do_nothing 188 | 189 | @wrapper 190 | @q 191 | @wrapper 192 | def decorated_log_bad(msg='default'): 193 | return msg 194 | 195 | decorated_log_bad('decorated bad message') 196 | self.assertInQLog(r"do_nothing\((?:\n\s*)?'" 197 | r"decorated bad message'\)") 198 | self.assertInQLog("-> 'decorated bad message'") 199 | 200 | def test_q_nested_good_wrappers(self): 201 | import q 202 | q.writer.color = False 203 | 204 | import functools 205 | 206 | def wrapper(func): 207 | def do_nothing(*args, **kwargs): 208 | return func(*args, **kwargs) 209 | return functools.update_wrapper(do_nothing, func) 210 | 211 | @wrapper 212 | @q 213 | @wrapper 214 | def decorated_log_good(msg='default'): 215 | return msg 216 | 217 | decorated_log_good('decorated good message') 218 | self.assertInQLog(r"decorated_log_good\((?:\n\s*)?'" 219 | r"decorated good message'\)") 220 | self.assertInQLog("-> 'decorated good message'") 221 | 222 | @unittest.skipIf(sys.version_info < (3, 3), "requires Python 3.3+") 223 | def test_q_trace_method(self): 224 | import q 225 | q.writer.color = False 226 | 227 | class A(object): 228 | @q 229 | def run1(self, arg): 230 | return arg 231 | 232 | @staticmethod 233 | @q 234 | def run2(arg): 235 | return arg 236 | 237 | @classmethod 238 | @q 239 | def run3(cls, arg): 240 | return arg 241 | 242 | a = A() 243 | a.run1('first message') 244 | A.run2('second message') 245 | A.run3('third message') 246 | 247 | self.assertInQLog(".*".join([ 248 | "\\bA.run1\\(", 249 | "'first message'\\)", 250 | ])) 251 | self.assertInQLog("-> 'first message'") 252 | 253 | self.assertInQLog(".*".join([ 254 | "\\bA.run2\\(", 255 | "'second message'\\)", 256 | ])) 257 | self.assertInQLog("-> 'second message'") 258 | 259 | self.assertInQLog(".*".join([ 260 | "\\bA.run3\\(", 261 | "'third message'\\)", 262 | ])) 263 | self.assertInQLog("-> 'third message'") 264 | 265 | 266 | unittest.main() 267 | --------------------------------------------------------------------------------