pax_global_header00006660000000000000000000000064141272754440014524gustar00rootroot0000000000000052 comment=4b37c2ee5e61ce2ae2efd50e086d19b4077b8d29 pprofile-2.1.0/000077500000000000000000000000001412727544400133445ustar00rootroot00000000000000pprofile-2.1.0/.gitattributes000066400000000000000000000000421412727544400162330ustar00rootroot00000000000000pprofile/_version.py export-subst pprofile-2.1.0/.gitignore000066400000000000000000000000461412727544400153340ustar00rootroot00000000000000dist/ build/ pprofile.egg-info/ *.pyc pprofile-2.1.0/COPYING000066400000000000000000000431031412727544400144000ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. pprofile-2.1.0/MANIFEST.in000066400000000000000000000001261412727544400151010ustar00rootroot00000000000000include COPYING include README.rst include versioneer.py include pprofile/_version.py pprofile-2.1.0/README.rst000066400000000000000000000460321412727544400150400ustar00rootroot00000000000000Line-granularity, thread-aware deterministic and statistic pure-python profiler Inspired from Robert Kern's line_profiler_ . Usage ===== As a command:: $ pprofile some_python_executable arg1 ... Once `some_python_executable` returns, prints annotated code of each file involved in the execution. As a command, ignoring any files from default `sys.path` (ie, python modules themselves), for shorter output:: $ pprofile --exclude-syspath some_python_executable arg1 ... Executing a module, like :code:`python -m`. `--exclude-syspath` is not recommended in this mode, as it will likely hide what you intend to profile. Also, explicitly ending pprofile arguments with `--` will prevent accidentally stealing command's arguments:: $ pprofile -m some_python_module -- arg1 ... As a module: .. code:: python import pprofile def someHotSpotCallable(): # Deterministic profiler prof = pprofile.Profile() with prof(): # Code to profile prof.print_stats() def someOtherHotSpotCallable(): # Statistic profiler prof = pprofile.StatisticalProfile() with prof( period=0.001, # Sample every 1ms single=True, # Only sample current thread ): # Code to profile prof.print_stats() For advanced usage, see :code:`pprofile --help` and :code:`pydoc pprofile`. Profiling overhead ------------------ pprofile default mode (`Deterministic profiling`_) has a large overhead. Part of the reason being that it is written to be as portable as possible (so no C extension). This large overhead can be an issue, which can be avoided by using `Statistic profiling`_ at the cost of some result readability decrease. Rule of thumb: +-----------------------------+----------------------------+------------------------+ | Code to profile runs for... | `Deterministic profiling`_ | `Statistic profiling`_ | +=============================+============================+========================+ | a few seconds | Yes | No [#]_ | +-----------------------------+----------------------------+------------------------+ | a few minutes | Maybe | Yes | +-----------------------------+----------------------------+------------------------+ | more (ex: daemon) | No | Yes [#]_ | +-----------------------------+----------------------------+------------------------+ Once you identified the hot spot and you decide you need finer-grained profiling to understand what needs fixing, you should try to make to-profile code run for shorter time so you can reasonably use deterministic profiling: use a smaller data set triggering the same code path, modify the code to only enable profiling on small pieces of code... .. [#] Statistic profiling will not have time to collect enough samples to produce usable output. .. [#] You may want to consider triggering pprofile from a signal handler or other IPC mechanism to profile a shorter subset. See `zpprofile.py` for how it can be used to profile code inside a running (zope) service (in which case the IPC mechanism is just Zope normal URL handling). Output ====== Supported output formats. Callgrind --------- The most useful output mode of pprofile is `Callgrind Profile Format`_, allows browsing profiling results with kcachegrind_ (or qcachegrind_ on Windows). :: $ pprofile --format callgrind --out cachegrind.out.threads demo/threads.py Callgrind format is implicitly enabled if ``--out`` basename starts with ``cachegrind.out.``, so above command can be simplified as:: $ pprofile --out cachegrind.out.threads demo/threads.py If you are analyzing callgrind traces on a different machine, you may want to use the ``--zipfile`` option to generate a zip file containing all files:: $ pprofile --out cachegrind.out.threads --zipfile threads_source.zip demo/threads.py Generated files will use relative paths, so you can extract generated archive in the same path as profiling result, and kcachegrind will load them - and not your system-wide files, which may differ. Annotated code -------------- Human-readable output, but can become difficult to use with large programs. :: $ pprofile demo/threads.py Profiling modes =============== Deterministic profiling ----------------------- In deterministic profiling mode, pprofile gets notified of each executed line. This mode generates very detailed reports, but at the cost of a large overhead. Also, profiling hooks being per-thread, either profiling must be enable before spawning threads (if you want to profile more than just the current thread), or profiled application must provide ways of enabling profiling afterwards - which is not very convenient. :: $ pprofile --threads 0 demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.00573s File: demo/threads.py File duration: 1.00168s (99.60%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 2| 3.21865e-05| 1.60933e-05| 0.00%|import threading 2| 1| 5.96046e-06| 5.96046e-06| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 2| 1.5974e-05| 7.98702e-06| 0.00%|def func(): 5| 1| 1.00111| 1.00111| 99.54%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 2| 2.00272e-05| 1.00136e-05| 0.00%|def func2(): 8| 1| 1.69277e-05| 1.69277e-05| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 1| 1.81198e-05| 1.81198e-05| 0.00%|t1 = threading.Thread(target=func) (call)| 1| 0.000610828| 0.000610828| 0.06%|# /usr/lib/python2.7/threading.py:436 __init__ 11| 1| 1.52588e-05| 1.52588e-05| 0.00%|t2 = threading.Thread(target=func) (call)| 1| 0.000438929| 0.000438929| 0.04%|# /usr/lib/python2.7/threading.py:436 __init__ 12| 1| 4.79221e-05| 4.79221e-05| 0.00%|t1.start() (call)| 1| 0.000843048| 0.000843048| 0.08%|# /usr/lib/python2.7/threading.py:485 start 13| 1| 6.48499e-05| 6.48499e-05| 0.01%|t2.start() (call)| 1| 0.00115609| 0.00115609| 0.11%|# /usr/lib/python2.7/threading.py:485 start 14| 1| 0.000205994| 0.000205994| 0.02%|(func(), func2()) (call)| 1| 1.00112| 1.00112| 99.54%|# demo/threads.py:4 func (call)| 1| 3.09944e-05| 3.09944e-05| 0.00%|# demo/threads.py:7 func2 15| 1| 7.62939e-05| 7.62939e-05| 0.01%|t1.join() (call)| 1| 0.000423908| 0.000423908| 0.04%|# /usr/lib/python2.7/threading.py:653 join 16| 1| 5.26905e-05| 5.26905e-05| 0.01%|t2.join() (call)| 1| 0.000320196| 0.000320196| 0.03%|# /usr/lib/python2.7/threading.py:653 join Note that time.sleep call is not counted as such. For some reason, python is not generating c_call/c_return/c_exception events (which are ignored by current code, as a result). Statistic profiling ------------------- In statistic profiling mode, pprofile periodically snapshots the current callstack(s) of current process to see what is being executed. As a result, profiler overhead can be dramatically reduced, making it possible to profile real workloads. Also, as statistic profiling acts at the whole-process level, it can be toggled independently of profiled code. The downside of statistic profiling is that output lacks timing information, which makes it harder to understand. :: $ pprofile --statistic .01 demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.0026s File: demo/threads.py File duration: 0s (0.00%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 0| 0| 0| 0.00%|import threading 2| 0| 0| 0| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 0| 0| 0| 0.00%|def func(): 5| 288| 0| 0| 0.00%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 0| 0| 0| 0.00%|def func2(): 8| 0| 0| 0| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 0| 0| 0| 0.00%|t1 = threading.Thread(target=func) 11| 0| 0| 0| 0.00%|t2 = threading.Thread(target=func) 12| 0| 0| 0| 0.00%|t1.start() 13| 0| 0| 0| 0.00%|t2.start() 14| 0| 0| 0| 0.00%|(func(), func2()) (call)| 96| 0| 0| 0.00%|# demo/threads.py:4 func 15| 0| 0| 0| 0.00%|t1.join() 16| 0| 0| 0| 0.00%|t2.join() File: /usr/lib/python2.7/threading.py File duration: 0s (0.00%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- [...] 308| 0| 0| 0| 0.00%| def wait(self, timeout=None): [...] 338| 0| 0| 0| 0.00%| if timeout is None: 339| 1| 0| 0| 0.00%| waiter.acquire() 340| 0| 0| 0| 0.00%| if __debug__: [...] 600| 0| 0| 0| 0.00%| def wait(self, timeout=None): [...] 617| 0| 0| 0| 0.00%| if not self.__flag: 618| 0| 0| 0| 0.00%| self.__cond.wait(timeout) (call)| 1| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:308 wait [...] 724| 0| 0| 0| 0.00%| def start(self): [...] 748| 0| 0| 0| 0.00%| self.__started.wait() (call)| 1| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:600 wait 749| 0| 0| 0| 0.00%| 750| 0| 0| 0| 0.00%| def run(self): [...] 760| 0| 0| 0| 0.00%| if self.__target: 761| 0| 0| 0| 0.00%| self.__target(*self.__args, **self.__kwargs) (call)| 192| 0| 0| 0.00%|# demo/threads.py:4 func 762| 0| 0| 0| 0.00%| finally: [...] 767| 0| 0| 0| 0.00%| def __bootstrap(self): [...] 780| 0| 0| 0| 0.00%| try: 781| 0| 0| 0| 0.00%| self.__bootstrap_inner() (call)| 192| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:790 __bootstrap_inner [...] 790| 0| 0| 0| 0.00%| def __bootstrap_inner(self): [...] 807| 0| 0| 0| 0.00%| try: 808| 0| 0| 0| 0.00%| self.run() (call)| 192| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:750 run Some details are lost (not all executed lines have a non-null hit-count), but the hot spot is still easily identifiable in this trivial example, and its call stack is still visible. Thread-aware profiling ====================== ``ThreadProfile`` class provides the same features as ``Profile``, but uses ``threading.settrace`` to propagate tracing to ``threading.Thread`` threads started after profiling is enabled. Limitations ----------- The time spent in another thread is not discounted from interrupted line. On the long run, it should not be a problem if switches are evenly distributed among lines, but threads executing fewer lines will appear as eating more CPU time than they really do. This is not specific to simultaneous multi-thread profiling: profiling a single thread of a multi-threaded application will also be polluted by time spent in other threads. Example (lines are reported as taking longer to execute when profiled along with another thread - although the other thread is not profiled):: $ demo/embedded.py Total duration: 1.00013s File: demo/embedded.py File duration: 1.00003s (99.99%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 0| 0| 0| 0.00%|#!/usr/bin/env python 2| 0| 0| 0| 0.00%|import threading 3| 0| 0| 0| 0.00%|import pprofile 4| 0| 0| 0| 0.00%|import time 5| 0| 0| 0| 0.00%|import sys 6| 0| 0| 0| 0.00%| 7| 1| 1.5974e-05| 1.5974e-05| 0.00%|def func(): 8| 0| 0| 0| 0.00%| # Busy loop, so context switches happen 9| 1| 1.40667e-05| 1.40667e-05| 0.00%| end = time.time() + 1 10| 146604| 0.511392| 3.48826e-06| 51.13%| while time.time() < end: 11| 146603| 0.48861| 3.33288e-06| 48.85%| pass 12| 0| 0| 0| 0.00%| 13| 0| 0| 0| 0.00%|# Single-treaded run 14| 0| 0| 0| 0.00%|prof = pprofile.Profile() 15| 0| 0| 0| 0.00%|with prof: 16| 0| 0| 0| 0.00%| func() (call)| 1| 1.00003| 1.00003| 99.99%|# ./demo/embedded.py:7 func 17| 0| 0| 0| 0.00%|prof.annotate(sys.stdout, __file__) 18| 0| 0| 0| 0.00%| 19| 0| 0| 0| 0.00%|# Dual-threaded run 20| 0| 0| 0| 0.00%|t1 = threading.Thread(target=func) 21| 0| 0| 0| 0.00%|prof = pprofile.Profile() 22| 0| 0| 0| 0.00%|with prof: 23| 0| 0| 0| 0.00%| t1.start() 24| 0| 0| 0| 0.00%| func() 25| 0| 0| 0| 0.00%| t1.join() 26| 0| 0| 0| 0.00%|prof.annotate(sys.stdout, __file__) Total duration: 1.00129s File: demo/embedded.py File duration: 1.00004s (99.88%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- [...] 7| 1| 1.50204e-05| 1.50204e-05| 0.00%|def func(): 8| 0| 0| 0| 0.00%| # Busy loop, so context switches happen 9| 1| 2.38419e-05| 2.38419e-05| 0.00%| end = time.time() + 1 10| 64598| 0.538571| 8.33728e-06| 53.79%| while time.time() < end: 11| 64597| 0.461432| 7.14324e-06| 46.08%| pass [...] This also means that the sum of the percentage of all lines can exceed 100%. It can reach the number of concurrent threads (200% with 2 threads being busy for the whole profiled execution time, etc). Example with 3 threads:: $ pprofile demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.00798s File: demo/threads.py File duration: 3.00604s (298.22%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 2| 3.21865e-05| 1.60933e-05| 0.00%|import threading 2| 1| 6.91414e-06| 6.91414e-06| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 4| 3.91006e-05| 9.77516e-06| 0.00%|def func(): 5| 3| 3.00539| 1.0018|298.16%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 2| 2.31266e-05| 1.15633e-05| 0.00%|def func2(): 8| 1| 2.38419e-05| 2.38419e-05| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 1| 1.81198e-05| 1.81198e-05| 0.00%|t1 = threading.Thread(target=func) (call)| 1| 0.000612974| 0.000612974| 0.06%|# /usr/lib/python2.7/threading.py:436 __init__ 11| 1| 1.57356e-05| 1.57356e-05| 0.00%|t2 = threading.Thread(target=func) (call)| 1| 0.000438213| 0.000438213| 0.04%|# /usr/lib/python2.7/threading.py:436 __init__ 12| 1| 6.60419e-05| 6.60419e-05| 0.01%|t1.start() (call)| 1| 0.000913858| 0.000913858| 0.09%|# /usr/lib/python2.7/threading.py:485 start 13| 1| 6.8903e-05| 6.8903e-05| 0.01%|t2.start() (call)| 1| 0.00167513| 0.00167513| 0.17%|# /usr/lib/python2.7/threading.py:485 start 14| 1| 0.000200272| 0.000200272| 0.02%|(func(), func2()) (call)| 1| 1.00274| 1.00274| 99.48%|# demo/threads.py:4 func (call)| 1| 4.19617e-05| 4.19617e-05| 0.00%|# demo/threads.py:7 func2 15| 1| 9.58443e-05| 9.58443e-05| 0.01%|t1.join() (call)| 1| 0.000411987| 0.000411987| 0.04%|# /usr/lib/python2.7/threading.py:653 join 16| 1| 5.29289e-05| 5.29289e-05| 0.01%|t2.join() (call)| 1| 0.000316143| 0.000316143| 0.03%|# /usr/lib/python2.7/threading.py:653 join Note that the call time is not added to file total: it's already accounted for inside "func". Why another profiler ? ====================== Python's standard profiling tools have a callable-level granularity, which means it is only possible to tell which function is a hot-spot, not which lines in that function. Robert Kern's line_profiler_ is a very nice alternative providing line-level profiling granularity, but in my opinion it has a few drawbacks which (in addition to the attractive technical challenge) made me start pprofile: - It is not pure-python. This choice makes sense for performance but makes usage with pypy difficult and requires installation (I value execution straight from checkout). - It requires source code modification to select what should be profiled. I prefer to have the option to do an in-depth, non-intrusive profiling. - As an effect of previous point, it does not have a notion above individual callable, annotating functions but not whole files - preventing module import profiling. - Profiling recursive code provides unexpected results (recursion cost is accumulated on callable's first line) because it doesn't track call stack. This may be unintended, and may be fixed at some point in line_profiler. .. _line_profiler: https://github.com/rkern/line_profiler .. _`Callgrind Profile Format`: http://valgrind.org/docs/manual/cl-format.html .. _kcachegrind: http://kcachegrind.sourceforge.net .. _qcachegrind: http://sourceforge.net/projects/qcachegrindwin/ pprofile-2.1.0/demo/000077500000000000000000000000001412727544400142705ustar00rootroot00000000000000pprofile-2.1.0/demo/embedded.py000077500000000000000000000007141412727544400164000ustar00rootroot00000000000000#!/usr/bin/env python import threading import pprofile import time import sys def func(): # Busy loop, so context switches happen end = time.time() + 1 while time.time() < end: pass # Single-treaded run prof = pprofile.Profile() with prof: func() prof.annotate(sys.stdout, __file__) # Dual-threaded run t1 = threading.Thread(target=func) prof = pprofile.Profile() with prof: t1.start() func() t1.join() prof.annotate(sys.stdout, __file__) pprofile-2.1.0/demo/empty.py000066400000000000000000000000001412727544400157660ustar00rootroot00000000000000pprofile-2.1.0/demo/encoding.py000066400000000000000000000001061412727544400164250ustar00rootroot00000000000000#!/usr/bin/env python import iso_8859_1 import utf_8 import utf_8_bom pprofile-2.1.0/demo/exceptions.py000066400000000000000000000006541412727544400170300ustar00rootroot00000000000000#!/usr/bin/env python def trigger(): raise Exception def indirect(): trigger() # Caught exception try: raise Exception except Exception: pass # Caught exception, from function try: trigger() except Exception: pass # Caught exception, from deeper function try: indirect() except Exception: pass # Uncaught exception, from function try: trigger() finally: pass print 'Never reached' pprofile-2.1.0/demo/iso_8859_1.py000066400000000000000000000001441412727544400163500ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # This is an iso-8859-1 "e" with acute accent: é pprofile-2.1.0/demo/module_globals.py000066400000000000000000000001201412727544400176230ustar00rootroot00000000000000# All these globals must be defined. __builtins__ __file__ __name__ __package__ pprofile-2.1.0/demo/recurse.py000066400000000000000000000001671412727544400163160ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 10 def foo(level=0): if level < MAX_LEVEL: foo(level + 1) sleep(0.01) foo() pprofile-2.1.0/demo/recurse2.py000066400000000000000000000002241412727544400163720ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 10 def boo(level=0): if level < MAX_LEVEL: baz(level + 1) sleep(0.01) def baz(level): boo(level) boo() pprofile-2.1.0/demo/recurse3.py000066400000000000000000000002111412727544400163670ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 5 def bar(level=0): if level < MAX_LEVEL: bar(level + 1) bar(level + 1) sleep(0.01) bar() pprofile-2.1.0/demo/recurse4.py000066400000000000000000000002341412727544400163750ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 5 def bar(level=0): if level < MAX_LEVEL: bar(level + 1) bar(level + 1) bar(level + 1) sleep(0.01) bar() pprofile-2.1.0/demo/the_main.py000066400000000000000000000001031412727544400164200ustar00rootroot00000000000000""" some docstring """ a_global_from_main = 'foo' import the_other pprofile-2.1.0/demo/the_other.py000066400000000000000000000001021412727544400166140ustar00rootroot00000000000000from __main__ import * # Must not raise print(a_global_from_main) pprofile-2.1.0/demo/threads.py000077500000000000000000000003501412727544400162750ustar00rootroot00000000000000#!/usr/bin/env python import threading import time def func(): time.sleep(1) def func2(): pass t1 = threading.Thread(target=func) t2 = threading.Thread(target=func) t1.start() t2.start() (func(), func2()) t1.join() t2.join() pprofile-2.1.0/demo/twocalls.py000066400000000000000000000001501412727544400164660ustar00rootroot00000000000000from time import sleep def bar(): sleep(0.1) def baz(): sleep(0.1) def foo(): bar() baz() foo() pprofile-2.1.0/demo/twocalls2.py000066400000000000000000000001201412727544400165450ustar00rootroot00000000000000from time import sleep def bar(): sleep(0.1) def foo(): bar() bar() foo() pprofile-2.1.0/demo/utf_8.py000066400000000000000000000001331412727544400156640ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: UTF-8 -*- # This is an utf-8 "e" with acute accent: é pprofile-2.1.0/demo/utf_8_bom.py000066400000000000000000000001061412727544400165210ustar00rootroot00000000000000#!/usr/bin/env python # This is an utf-8 "e" with acute accent: é pprofile-2.1.0/pprofile/000077500000000000000000000000001412727544400151645ustar00rootroot00000000000000pprofile-2.1.0/pprofile/__init__.py000077500000000000000000001560701412727544400173110ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2013-2020 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ pprofile - Line-granularity, thread-aware deterministic and statistic pure-python profiler Usage as a command line: $ pprofile --exclude-syspath some_python_executable arg1 ... $ pprofile --exclude-syspath -m some_python_module -- arg1 ... $ python -m pprofile --exclude-syspath some_python_executable arg1 ... $ python -m pprofile -m some_python_module -- arg1 ... See --help for all options. Usage as a python module: Deterministic profiling: >>> prof = pprofile.Profile() >>> with prof(): >>> # Code to profile >>> prof.print_stats() Statistic profiling: >>> prof = StatisticalProfile() >>> with prof(): >>> # Code to profile >>> prof.print_stats() """ from __future__ import print_function, division, absolute_import from collections import defaultdict, deque from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.encoders import encode_quopri from functools import partial, wraps # Note: use time, not clock. # Clock, at least on linux, ignores time not spent executing code # (ex: time.sleep()). The goal of pprofile is not to profile python code # execution as such (ie, to improve python interpreter), but to profile a # possibly complex application, with its (IO) waits, sleeps, (...) so a # developper can understand what is slow rather than what keeps the cpu busy. # So using the wall-clock as a way to measure time spent is more meaningful. # XXX: This said, if time() lacks precision, a better but likely # platform-dependent wall-clock time source must be identified and used. from time import time from warnings import warn import argparse import io import inspect from itertools import count import linecache import os # not caught by 2to3, likely because pipes.quote is not documented in python 2 try: from pipes import quote as shlex_quote # Python 2 except ImportError: from shlex import quote as shlex_quote # Python 3 import platform import re import runpy import shlex from subprocess import list2cmdline as windows_list2cmdline import sys import threading import zipfile try: from IPython.core.magic import register_line_cell_magic except ImportError: register_line_cell_magic = lambda x: x __all__ = ( 'ProfileBase', 'ProfileRunnerBase', 'Profile', 'ThreadProfile', 'StatisticProfile', 'StatisticThread', 'run', 'runctx', 'runfile', 'runpath', ) class BaseLineIterator(object): def __init__(self, getline, filename, global_dict): self._getline = getline self._filename = filename self._global_dict = global_dict self._lineno = 1 def __iter__(self): return self def __next__(self): lineno = self._lineno self._lineno += 1 return lineno, self._getline(self._filename, lineno, self._global_dict) next = __next__ # BBB 2.7 if sys.version_info < (3, ): import codecs # Find coding specification (see PEP-0263) _matchCoding = re.compile( r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)', ).match class LineIterator(BaseLineIterator): _encoding = None def __init__(self, *args, **kw): super(LineIterator, self).__init__(*args, **kw) # Identify encoding. first_line = self._getline(self._filename, 1, self._global_dict) if isinstance(first_line, bytes): # BOM - python2 only detects the (discouraged) UTF-8 BOM if first_line.startswith(codecs.BOM_UTF8): self._encoding = 'utf-8' else: # PEP-0263: "the first or second line must match [_matchCoding]" match = _matchCoding(first_line) if match is None: match = _matchCoding( self._getline(self._filename, 2, self._global_dict), ) if match is None: self._encoding = 'ascii' else: self._encoding = match.group(1) # else, first line is unicode. def __next__(self): lineno, line = super(LineIterator, self).__next__() if self._encoding: line = line.decode(self._encoding, errors='replace') return lineno, line next = __next__ # BBB def iterframes(current_frames): return current_frames().iteritems() else: # getline returns unicode objects, nothing to do LineIterator = BaseLineIterator unicode = basestring = str def iterframes(current_frames): return current_frames().items() if platform.system() == 'Windows': quoteCommandline = windows_list2cmdline else: def quoteCommandline(commandline): return ' '.join(shlex_quote(x) for x in commandline) class EncodeOrReplaceWriter(object): """ Write-only file-ish object which replaces unsupported chars when underlying file rejects them. """ def __init__(self, out): self._encoding = getattr(out, 'encoding', None) or 'ascii' self._write = out.write def write(self, data): try: self._write(data) except UnicodeEncodeError: self._write( data.encode( self._encoding, errors='replace', ).decode(self._encoding), ) def _isCallgrindName(filepath): return os.path.basename(filepath).startswith('cachegrind.out.') class _FileTiming(object): """ Accumulation of profiling statistics (line and call durations) for a given source "file" (unique global dict). Subclasses should be aware that: - this classes uses __slots__, mainly for cpu efficiency (property lookup is in a list instead of a dict) - it can access the BaseProfile instance which created any instace using the "profiler" property, should they share some state across source files. - methods on this class are profiling choke-point - keep customisations as cheap in CPU as you can ! """ __slots__ = ('line_dict', 'call_dict', 'filename', 'global_dict', 'profiler') def __init__(self, filename, global_dict, profiler): self.filename = filename self.global_dict = global_dict self.line_dict = defaultdict(lambda: defaultdict(lambda: [0, 0])) self.call_dict = {} # Note: not used in this implementation, may be used by subclasses. self.profiler = profiler def hit(self, code, line, duration): """ A line has finished executing. code (code) container function's code object line (int) line number of just executed line duration (float) duration of the line, in seconds """ entry = self.line_dict[line][code] entry[0] += 1 entry[1] += duration def call(self, code, line, callee_file_timing, callee, duration, frame): """ A call originating from this file returned. code (code) caller's code object line (int) caller's line number callee_file_timing (FileTiming) callee's FileTiming callee (code) callee's code object duration (float) duration of the call, in seconds frame (frame) calle's entire frame as of its return """ try: entry = self.call_dict[(code, line, callee)] except KeyError: self.call_dict[(code, line, callee)] = [callee_file_timing, 1, duration] else: entry[1] += 1 entry[2] += duration def getHitStatsFor(self, line): total_hits = total_duration = 0 for hits, duration in self.line_dict.get(line, {}).values(): total_hits += hits total_duration += duration return total_hits, total_duration def getLastLine(self): return max( max(self.line_dict) if self.line_dict else 0, max(x for _, x, _ in self.call_dict) if self.call_dict else 0, ) def iterHits(self): for line, code_dict in self.line_dict.items(): for code, (hits, duration) in code_dict.items(): yield line, code, hits, duration def iterCalls(self): for (code, line, callee), (callee_file_timing, hit, duration) in \ self.call_dict.items(): yield ( line, code, hit, duration, callee_file_timing.filename, callee, ) def getCallListByLine(self): result = defaultdict(list) for line, code, hit, duration, callee_filename, callee in self.iterCalls(): result[line].append(( code, hit, duration, callee_filename, callee, )) return result def getTotalTime(self): return sum( y[1] for x in self.line_dict.values() for y in x.values() ) def getTotalHitCount(self): return sum( y[0] for x in self.line_dict.values() for y in x.values() ) def getSortKey(self): # total duration first, then total hit count for statistical profiling result = [0, 0] for entry in self.line_dict.values(): for hit, duration in entry.values(): result[0] += duration result[1] += hit return result FileTiming = _FileTiming class LocalDescriptor(threading.local): """ Implementation of descriptor API for thread-local properties. """ def __init__(self, func=None): """ func (callable) If provided, called when a missing property is accessed (ex: accessing thread never initialised that property). If None, AttributeError is raised. """ super(LocalDescriptor, self).__init__() if func is not None: self.func = func def __get__(self, instance, owner): try: return getattr(self, str(id(instance))) except AttributeError: # Raises AttributeError if func was not provided. value = self.func() setattr(self, str(id(instance)), value) return value def __set__(self, instance, value): setattr(self, str(id(instance)), value) def __delete__(self, instance): try: delattr(self, str(id(instance))) except AttributeError: pass _ANNOTATE_HEADER = \ u'%6s|%10s|' \ u'%13s|%13s|%7s|' \ u'Source code' % ( u'Line #', u'Hits', u'Time', u'Time per hit', u'%', ) _ANNOTATE_HORIZONTAL_LINE = u''.join(x == u'|' and u'+' or u'-' for x in _ANNOTATE_HEADER) _ANNOTATE_FORMAT = \ u'%(lineno)6i|%(hits)10i|' \ u'%(time)13g|%(time_per_hit)13g|%(percent)6.2f%%|' \ u'%(line)s' _ANNOTATE_CALL_FORMAT = \ u'(call)|%(hits)10i|' \ u'%(time)13g|%(time_per_hit)13g|%(percent)6.2f%%|' \ u'# %(callee_file)s:%(callee_line)s %(callee_name)s' def _initStack(): # frame_time: when current frame execution started/resumed last # frame_discount: time discounted from current frame, because it appeared # lower in the call stack from the same callsite # lineno: latest line which execution started # line_time: time at which latest line started being executed # line_duration: total time spent in current line up to last resume now = time() return (deque([[now, 0, None, now, 0]]), defaultdict(deque)) class ProfileBase(object): """ Methods common to deterministic and statistic profiling. Subclasses can override the "FileTiming" property to use a different class. """ __slots__ = ( 'file_dict', 'global_dict', 'total_time', '__dict__', '__weakref__', 'merged_file_dict', ) FileTiming = _FileTiming def __init__(self): self.file_dict = {} self.merged_file_dict = {} self.global_dict = {} self.total_time = 0 def _getFileTiming(self, frame): try: return self.global_dict[id(frame.f_globals)] except KeyError: f_globals = frame.f_globals name = self._getFilename(frame) self.global_dict[id(f_globals)] = file_timing = self.FileTiming( name, f_globals, self, ) # file_dict modifications must be thread-safe to not lose measures. # setdefault is atomic, append is atomic. self.file_dict.setdefault(name, []).append(file_timing) return file_timing @staticmethod def _getFilename(frame): """ Overload in subclasses to customise filename generation. """ return frame.f_code.co_filename @staticmethod def _getline(filename, lineno, global_dict): """ Overload in subclasses to customise source retrieval. """ return linecache.getline(filename, lineno, global_dict) def _mergeFileTiming(self, rebuild=False): merged_file_dict = self.merged_file_dict if merged_file_dict and not rebuild: return merged_file_dict merged_file_dict.clear() # Regroup by module, to find all duplicates from other threads. by_global_dict = defaultdict(list) for file_timing_list in self.file_dict.values(): for file_timing in file_timing_list: by_global_dict[ id(file_timing.global_dict) ].append( file_timing, ) # Resolve name conflicts. global_to_named_dict = {} for global_dict_id, file_timing_list in by_global_dict.items(): file_timing = file_timing_list[0] name = file_timing.filename if name in merged_file_dict: counter = count() base_name = name while name in merged_file_dict: name = base_name + '_%i' % next(counter) global_to_named_dict[global_dict_id] = merged_file_dict[name] = FileTiming( name, file_timing.global_dict, file_timing.profiler, # Note: should be self ) # Add all file timings from one module together under its # deduplicated name. This needs to happen after all names # are generated and all empty file timings are created so # call events cross-references can be remapped. for merged_file_timing in merged_file_dict.values(): line_dict = merged_file_timing.line_dict for file_timing in by_global_dict[id(merged_file_timing.global_dict)]: for line, other_code_dict in file_timing.line_dict.items(): code_dict = line_dict[line] for code, ( other_hits, other_duration, ) in other_code_dict.items(): entry = code_dict[code] entry[0] += other_hits entry[1] += other_duration call_dict = merged_file_timing.call_dict for key, ( other_callee_file_timing, other_hits, other_duration, ) in file_timing.call_dict.items(): try: entry = call_dict[key] except KeyError: entry = call_dict[key] = [ global_to_named_dict[ id(other_callee_file_timing.global_dict) ], other_hits, other_duration, ] else: entry[1] += other_hits entry[2] += other_duration return merged_file_dict def getFilenameSet(self): """ Returns a set of profiled file names. Note: "file name" is used loosely here. See python documentation for co_filename, linecache module and PEP302. It may not be a valid filesystem path. """ result = set(self._mergeFileTiming()) # Ignore profiling code. __file__ does not always provide consistent # results with f_code.co_filename (ex: easy_install with zipped egg), # so inspect current frame instead. # Get current file from one of pprofile methods. Compatible with # implementations that do not have the inspect.currentframe() method # (e.g. IronPython). # XXX: Assumes that all of pprofile code is in a single file. # XXX: Assumes that _initStack exists in pprofile module. result.discard(inspect.getsourcefile(_initStack)) return result def _getFileNameList(self, filename, may_sort=True): if filename is None: filename = self.getFilenameSet() elif isinstance(filename, basestring): return [filename] if may_sort: try: # Detect if filename is an ordered data type. filename[:0] except TypeError: # Not ordered, sort. file_dict = self._mergeFileTiming() filename = sorted(filename, reverse=True, key=lambda x: file_dict[x].getSortKey() ) return filename def _iterOutFiles(self, filename=None, commandline=None): """ Yields path, data, mimetype for each file involved on or produced by profiling. """ out = io.StringIO() self.callgrind( out, filename=filename, commandline=commandline, relative_path=True, ) yield ( 'cachegrind.out.pprofile', out.getvalue(), 'application/x-kcachegrind', ) for name in self._getFileNameList(filename, may_sort=False): lines = ''.join(self._iterRawFile(name)) if lines: if isinstance(lines, unicode): lines = lines.encode('utf-8') yield ( _relpath(name), lines, 'text/x-python', ) def getCallgrindMIME(self, out, filename=None, commandline=None, relative_path=True): """ Write to "out" a mime-multipart representation of: - callgrind profiling statistics (cachegrind.out.pprofile) - all involved python code, including Python Scripts without hierarchy (the rest) and return its mimetype. To unpack resulting file, see "unpack a MIME message" in http://docs.python.org/2/library/email-examples.html Or get demultipart from https://pypi.python.org/pypi/demultipart relative_path: Ignored. """ _ = relative_path result = MIMEMultipart() base_type_dict = { 'application': MIMEApplication, 'text': MIMEText, } encoder_dict = { 'application/x-kcachegrind': encode_quopri, 'text/x-python': 'utf-8', 'text/plain': 'utf-8', } for path, data, mimetype in self._iterOutFiles( filename=filename, commandline=commandline, ): base_type, sub_type = mimetype.split('/') chunk = base_type_dict[base_type]( data, sub_type, encoder_dict.get(mimetype), ) chunk.add_header( 'Content-Disposition', 'attachment', filename=path, ) result.attach(chunk) out.write(result.as_string()) return result['content-type'] def getCallgrindZip(self, out=None, filename=None, commandline=None, relative_path=True): """ Write to "out" a serialised zip archive containing: - callgrind profiling statistics (cachegrind.out.pprofile) - all involved python code, including Python Scripts without hierarchy (the rest) as a byte string and the "application/zip" mimetype. relative_path: Ignored. """ _ = relative_path with zipfile.ZipFile( out, mode='w', compression=zipfile.ZIP_DEFLATED, ) as outfile: for path, data, _ in self._iterOutFiles( filename=filename, commandline=commandline, ): outfile.writestr(path, data) return 'application/zip' def callgrind(self, out, filename=None, commandline=None, relative_path=False): """ Dump statistics in callgrind format. Contains: - per-line hit count, time and time-per-hit - call associations (call tree) Note: hit count is not inclusive, in that it is not the sum of all hits inside that call. Time unit: microsecond (1e-6 second). out (file-ish opened for writing) Destination of callgrind profiling data. Encoding should be chosen to be able to represent characters in filesystem path and (when provided) commandline. Setting an encoding error handler other than "raise" (default) will likely result in profiling results being unable to locate code for annotation. filename (str, collection of str) If provided, dump stats for given source file(s) only. By default, list for all known files. commandline (anything with __str__) If provided, will be output as the command line used to generate this profiling data. relative_path (bool) When True, absolute elements are stripped from path. Useful when maintaining several copies of source trees with their own profiling result, so kcachegrind does not look in system-wide files which may not match with profiled code. """ print(u'# callgrind format', file=out) print(u'version: 1', file=out) print(u'creator: pprofile', file=out) print(u'event: usphit :microseconds/hit', file=out) print(u'events: hits microseconds usphit', file=out) if commandline is not None: print(u'cmd:', commandline, file=out) file_dict = self._mergeFileTiming() if relative_path: convertPath = _relpath else: convertPath = lambda x: x if os.path.sep != "/": # qCacheGrind (windows build) needs at least one UNIX separator # in path to find the file. Adapt here even if this is probably # more of a qCacheGrind issue... convertPath = lambda x, cascade=convertPath: cascade( '/'.join(x.split(os.path.sep)) ) code_to_name_dict = {} homonym_counter = {} def getCodeName(filename, code): # Tracks code objects globally, because callee information needs # to be consistent accross files. # Inside a file, grants unique names to each code object. try: return code_to_name_dict[code] except KeyError: name = code.co_name + ':%i' % code.co_firstlineno key = (filename, name) homonym_count = homonym_counter.get(key, 0) if homonym_count: name += '_%i' % homonym_count homonym_counter[key] = homonym_count + 1 code_to_name_dict[code] = name return name for current_file in self._getFileNameList(filename, may_sort=False): file_timing = file_dict[current_file] print(u'fl=%s' % convertPath(current_file), file=out) # When a local callable is created an immediately executed, this # loop would start a new "fn=" section but would not end it before # emitting "cfn=" lines, making the callee appear as not being # called by interrupted "fn=" section. # So dispatch all functions in a first pass, and build # uninterrupted sections in a second pass. # Note: cost line is a list just to be mutable. A single item is # expected. func_dict = defaultdict(lambda: defaultdict(lambda: ([], []))) for lineno, code, hits, duration in file_timing.iterHits(): func_dict[getCodeName(current_file, code)][lineno][0].append( (hits, int(duration * 1000000)), ) for ( lineno, caller, call_hits, call_duration, callee_file, callee, ) in file_timing.iterCalls(): call_ticks = int(call_duration * 1000000) func_call_list = func_dict[ getCodeName(current_file, caller) ][lineno][1] append = func_call_list.append append(u'cfl=' + convertPath(callee_file)) append(u'cfn=' + getCodeName(callee_file, callee)) append(u'calls=%i %i' % (call_hits, callee.co_firstlineno)) append(u'%i %i %i %i' % (lineno, call_hits, call_ticks, call_ticks // call_hits)) for func_name, line_dict in func_dict.items(): print(u'fn=%s' % func_name, file=out) for lineno, (func_hit_list, func_call_list) in sorted(line_dict.items()): if func_hit_list: # Multiple function objects may "reside" on the same # line of the same file (same global dict). # Sum these up and produce a single cachegrind event. hits = sum(x for x, _ in func_hit_list) ticks = sum(x for _, x in func_hit_list) print( u'%i %i %i %i' % ( lineno, hits, ticks, ticks // hits, ), file=out, ) for line in func_call_list: print(line, file=out) def annotate(self, out, filename=None, commandline=None, relative_path=False): """ Dump annotated source code with current profiling statistics to "out" file. Time unit: second. out (file-ish opened for writing) Destination of annotated sources. Encoding and encoding error handling should be chosen so as to be able to represent all characters present in source code (ex: utf-8, or ascii with "replace" error handler). filename (str, collection of str) If provided, dump stats for given source file(s) only. If unordered collection, it will get sorted by decreasing total file score (total time if available, then total hit count). By default, list for all known files. commandline (anything with __str__) If provided, will be output as the command line used to generate this annotation. relative_path (bool) For compatibility with callgrind. Ignored. """ file_dict = self._mergeFileTiming() total_time = self.total_time if commandline is not None: print(u'Command line:', commandline, file=out) print(u'Total duration: %gs' % total_time, file=out) if not total_time: return def percent(value, scale): if scale == 0: return 0 return value * 100 / scale for name in self._getFileNameList(filename): file_timing = file_dict[name] file_total_time = file_timing.getTotalTime() call_list_by_line = file_timing.getCallListByLine() print(u'File: %s' % name, file=out) print(u'File duration: %gs (%.2f%%)' % (file_total_time, percent(file_total_time, total_time)), file=out) print(_ANNOTATE_HEADER, file=out) print(_ANNOTATE_HORIZONTAL_LINE, file=out) last_line = file_timing.getLastLine() for lineno, line in LineIterator( self._getline, file_timing.filename, file_timing.global_dict, ): if not line and lineno > last_line: break hits, duration = file_timing.getHitStatsFor(lineno) print(_ANNOTATE_FORMAT % { u'lineno': lineno, u'hits': hits, u'time': duration, u'time_per_hit': duration / hits if hits else 0, u'percent': percent(duration, total_time), u'line': (line or u'').rstrip(), }, file=out) for ( _, call_hits, call_duration, callee_file, callee, ) in call_list_by_line.get(lineno, ()): print(_ANNOTATE_CALL_FORMAT % { u'hits': call_hits, u'time': call_duration, u'time_per_hit': call_duration / call_hits, u'percent': percent(call_duration, total_time), u'callee_file': callee_file, u'callee_line': callee.co_firstlineno, u'callee_name': callee.co_name, }, file=out) def _iterRawFile(self, name): file_timing = self._mergeFileTiming()[name] for lineno in count(1): line = self._getline(file_timing.filename, lineno, file_timing.global_dict) if not line: break yield line def iterSource(self): """ Iterator over all involved files. Yields 2-tuple composed of file path and an iterator over (non-annotated) source lines. Can be used to generate a file tree for use with kcachegrind, for example. """ for name in self.getFilenameSet(): yield name, self._iterRawFile(name) # profile/cProfile-like API def dump_stats(self, filename): """ Similar to profile.Profile.dump_stats - but different output format ! """ if _isCallgrindName(filename): with open(filename, 'w') as out: self.callgrind(out) else: with io.open(filename, 'w', errors='replace') as out: self.annotate(out) def print_stats(self): """ Similar to profile.Profile.print_stats . Returns None. """ self.annotate(EncodeOrReplaceWriter(sys.stdout)) class ProfileRunnerBase(object): def __call__(self): return self def __enter__(self): raise NotImplementedError def __exit__(self, exc_type, exc_val, exc_tb): raise NotImplementedError # profile/cProfile-like API def runctx(self, cmd, globals, locals): """Similar to profile.Profile.runctx .""" with self(): exec(cmd, globals, locals) return self def runcall(self, func, *args, **kw): """Similar to profile.Profile.runcall .""" with self(): return func(*args, **kw) def runfile(self, fd, argv, fd_name='', compile_flags=0, dont_inherit=1, globals={}): with fd: code = compile(fd.read(), fd_name, 'exec', flags=compile_flags, dont_inherit=dont_inherit) original_sys_argv = list(sys.argv) for name, docstring in zip(code.co_names, code.co_consts): if name == '__doc__': break else: docstring = None original_main = sys.modules.get('__main__') # XXX: is there a better way to get hold of module type ? code_module = type(original_main)('__main__', docstring) ctx_globals = code_module.__dict__ ctx_globals.update(globals) ctx_globals['__builtins__'] = __builtins__ ctx_globals['__file__'] = fd_name ctx_globals['__name__'] = '__main__' ctx_globals['__package__'] = None sys.modules['__main__'] = code_module try: sys.argv[:] = argv return self.runctx(code, ctx_globals, None) finally: sys.argv[:] = original_sys_argv sys.modules['__main__'] = original_main def runpath(self, path, argv): original_sys_path = list(sys.path) try: sys.path.insert(0, os.path.dirname(path)) return self.runfile(open(path, 'rb'), argv, fd_name=path) finally: sys.path[:] = original_sys_path def runmodule(self, module, argv): original_sys_argv = list(sys.argv) original_sys_path0 = sys.path[0] try: sys.path[0] = os.getcwd() sys.argv[:] = argv with self(): runpy.run_module(module, run_name='__main__', alter_sys=True) finally: sys.argv[:] = original_sys_argv sys.path[0] = original_sys_path0 return self class Profile(ProfileBase, ProfileRunnerBase): """ Deterministic, recursive, line-granularity, profiling class. Does not require any source code change to work. If the performance hit is too large, it can benefit from some integration (calling enable/disable around selected code chunks). The sum of time spent in all profiled lines is less than the total profiled time reported. This is (part of) profiling overhead. This also mans that sum of time-spent-on-line percentage is less than 100%. All times are "internal time", ie they do not count time spent inside called (profilable, so python) functions. """ __slots__ = ( '_global_trace', '_local_trace', 'stack', 'enabled_start', ) def __init__(self, verbose=False): super(Profile, self).__init__() if verbose: def decorator(func): @wraps(func) def wrapper(frame, event, arg, _traceEvent=self._traceEvent): _traceEvent(frame, event) return func(frame, event, arg) return wrapper self._global_trace = decorator(self._real_global_trace) self._local_trace = decorator(self._real_local_trace) else: self._global_trace = self._real_global_trace self._local_trace = self._real_local_trace self.stack = None self.enabled_start = None def _enable(self): """ Overload this method when subclassing. Called before actually enabling trace. """ self.stack = _initStack() self.enabled_start = time() def enable(self): """ Enable profiling. """ if self.enabled_start: warn('Duplicate "enable" call') else: self._enable() sys.settrace(self._global_trace) def _disable(self): """ Overload this method when subclassing. Called after actually disabling trace. """ self.total_time += time() - self.enabled_start self.enabled_start = None self.stack = None def disable(self): """ Disable profiling. """ if self.enabled_start: sys.settrace(None) self._disable() else: warn('Duplicate "disable" call') def __enter__(self): """ __enter__() -> self """ self.enable() return self def __exit__(self, exc_type, exc_val, exc_tb): """ __exit__(*excinfo) -> None. Disables profiling. """ self.disable() def _traceEvent(self, frame, event): f_code = frame.f_code lineno = frame.f_lineno print('%10.6f%s%s %s:%s %s+%s' % ( time() - self.enabled_start, ' ' * len(self.stack[0]), event, f_code.co_filename, lineno, f_code.co_name, lineno - f_code.co_firstlineno, ), file=sys.stderr) def _real_global_trace(self, frame, event, arg): local_trace = self._local_trace if local_trace is not None: event_time = time() callee_entry = [event_time, 0, frame.f_lineno, event_time, 0] try: stack, callee_dict = self.stack except TypeError: return None try: caller_entry = stack[-1] except IndexError: pass else: # Suspend caller frame frame_time, frame_discount, lineno, line_time, line_duration = caller_entry caller_entry[4] = event_time - line_time + line_duration callee_dict[(frame.f_back.f_code, frame.f_code)].append(callee_entry) stack.append(callee_entry) return local_trace def _real_local_trace(self, frame, event, arg): if event == 'line' or event == 'return': event_time = time() try: stack, callee_dict = self.stack except TypeError: return None try: stack_entry = stack[-1] except IndexError: warn('Profiling stack underflow, disabling.') self.disable() return None frame_time, frame_discount, lineno, line_time, line_duration = stack_entry file_timing = self._getFileTiming(frame) file_timing.hit(frame.f_code, lineno, event_time - line_time + line_duration) if event == 'line': # Start a new line stack_entry[2] = frame.f_lineno stack_entry[3] = event_time stack_entry[4] = 0 else: # 'return' event, is still callee # Resume caller frame stack.pop() stack[-1][3] = event_time caller_frame = frame.f_back caller_code = caller_frame.f_code callee_code = frame.f_code callee_entry_list = callee_dict[(caller_code, callee_code)] callee_entry_list.pop() call_duration = event_time - frame_time if callee_entry_list: # Callee is also somewhere up the stack, so discount this # call duration from it. callee_entry_list[-1][1] += call_duration self._getFileTiming(caller_frame).call( caller_code, caller_frame.f_lineno, file_timing, callee_code, call_duration - frame_discount, frame, ) return self._local_trace # profile/cProfile-like API def run(self, cmd): """Similar to profile.Profile.run .""" from . import __main__ dikt = __main__.__dict__ return self.runctx(cmd, dikt, dikt) class ThreadProfile(Profile): """ threading.Thread-aware version of Profile class. Threads started after enable() call will be profiled. After disable() call, threads will need to be switched into and trigger a trace event (typically a "line" event) before they can notice the disabling. """ __slots__ = ('_local_trace_backup', ) stack = LocalDescriptor(_initStack) global_dict = LocalDescriptor(dict) def __init__(self, **kw): super(ThreadProfile, self).__init__(**kw) self._local_trace_backup = self._local_trace def _enable(self): self._local_trace = self._local_trace_backup threading.settrace(self._global_trace) super(ThreadProfile, self)._enable() def _disable(self): super(ThreadProfile, self)._disable() threading.settrace(None) self._local_trace = None class StatisticProfile(ProfileBase, ProfileRunnerBase): """ Statistic profiling class. This class does not gather its own samples by itself. Instead, it must be provided with call stacks (as returned by sys._getframe() or sys._current_frames()). """ def sample(self, frame): getFileTiming = self._getFileTiming called_timing = getFileTiming(frame) called_code = frame.f_code called_timing.hit(called_code, frame.f_lineno, 0) while True: caller = frame.f_back if caller is None: break caller_timing = getFileTiming(caller) caller_code = caller.f_code caller_timing.call(caller_code, caller.f_lineno, called_timing, called_code, 0, frame) called_timing = caller_timing frame = caller called_code = caller_code def __call__(self, period=.001, single=True, group=None, name=None): """ Instanciate StatisticThread. >>> s_profile = StatisticProfile() >>> with s_profile(single=False): >>> # Code to profile Is equivalent to: >>> s_profile = StatisticProfile() >>> s_thread = StatisticThread(profiler=s_profile, single=False) >>> with s_thread: >>> # Code to profile """ return StatisticThread( profiler=self, period=period, single=single, group=group, name=name, ) # BBB StatisticalProfile = StatisticProfile class StatisticThread(threading.Thread, ProfileRunnerBase): """ Usage in a nutshell: with StatisticThread() as profiler_thread: # do stuff profiler_thread.profiler.print_stats() """ __slots__ = ( '_test', '_start_time', 'clean_exit', ) def __init__(self, profiler=None, period=.001, single=True, group=None, name=None): """ profiler (None or StatisticProfile instance) Available on instances as the "profiler" read-only property. If None, a new profiler instance will be created. period (float) How many seconds to wait between consecutive samples. The smaller, the more profiling overhead, but the faster results become meaningful. The larger, the less profiling overhead, but requires long profiling session to get meaningful results. single (bool) Profile only the thread which created this instance. group, name See Python's threading.Thread API. """ if profiler is None: profiler = StatisticProfile() if single: self._test = lambda x, ident=threading.current_thread().ident: ident == x else: self._test = None super(StatisticThread, self).__init__( group=group, name=name, ) self._stop_event = threading.Event() self._period = period self._profiler = profiler profiler.total_time = 0 self.daemon = True self.clean_exit = False @property def profiler(self): return self._profiler def start(self): self.clean_exit = False self._can_run = True self._start_time = time() super(StatisticThread, self).start() def stop(self): """ Request thread to stop. Does not wait for actual termination (use join() method). """ if self.is_alive(): self._can_run = False self._stop_event.set() self._profiler.total_time += time() - self._start_time self._start_time = None def __enter__(self): """ __enter__() -> self """ self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): """ __exit__(*excinfo) -> None. Stops and joins profiling thread. """ self.stop() self.join() def run(self): current_frames = sys._current_frames test = self._test if test is None: test = lambda x, ident=threading.current_thread().ident: ident != x sample = self._profiler.sample stop_event = self._stop_event wait = partial(stop_event.wait, self._period) while self._can_run: for ident, frame in iterframes(current_frames=current_frames): if test(ident): sample(frame) frame = None wait() stop_event.clear() self.clean_exit = True def callgrind(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.callgrind(*args, **kw) def annotate(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.annotate(*args, **kw) def dump_stats(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.dump_stats(*args, **kw) def print_stats(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.print_stats(*args, **kw) def iterSource(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.iterSource(*args, **kw) # BBB StatisticalThread = StatisticThread # profile/cProfile-like API (no sort parameter !) def _run(threads, verbose, func_name, filename, *args, **kw): if threads: klass = ThreadProfile else: klass = Profile prof = klass(verbose=verbose) try: try: getattr(prof, func_name)(*args, **kw) except SystemExit: pass finally: if filename is None: prof.print_stats() else: prof.dump_stats(filename) def run(cmd, filename=None, threads=True, verbose=False): """Similar to profile.run .""" _run(threads, verbose, 'run', filename, cmd) def runctx(cmd, globals, locals, filename=None, threads=True, verbose=False): """Similar to profile.runctx .""" _run(threads, verbose, 'runctx', filename, cmd, globals, locals) def runfile(fd, argv, fd_name='', compile_flags=0, dont_inherit=1, filename=None, threads=True, verbose=False): """ Run code from given file descriptor with profiling enabled. Closes fd before executing contained code. """ _run(threads, verbose, 'runfile', filename, fd, argv, fd_name, compile_flags, dont_inherit) def runpath(path, argv, filename=None, threads=True, verbose=False): """ Run code from open-accessible file path with profiling enabled. """ _run(threads, verbose, 'runpath', filename, path, argv) _allsep = os.sep + (os.altsep or '') def _relpath(name): """ Strip absolute components from path. Inspired from zipfile.write(). """ return os.path.normpath(os.path.splitdrive(name)[1]).lstrip(_allsep) def main(argv=None, stdin=None): if argv is None: argv = sys.argv format_dict = { 'text': 'annotate', 'callgrind': 'callgrind', 'callgrindzip': 'getCallgrindZip', } parser = argparse.ArgumentParser(argv[0]) parser.add_argument('script', help='Python script to execute (optionaly ' 'followed by its arguments)', nargs='?') parser.add_argument('argv', nargs=argparse.REMAINDER) parser.add_argument('-o', '--out', default='-', help='Write annotated sources to this file. Defaults to stdout.') parser.add_argument('-z', '--zipfile', help='Name of a zip file to generate from all involved source files. ' 'Useful with callgrind output.') parser.add_argument('-t', '--threads', default=1, type=int, help='If ' 'non-zero, trace threads spawned by program. Default: %(default)s') parser.add_argument('-f', '--format', choices=format_dict, help='Format in which output is generated. If not set, auto-detected ' 'from filename if provided, falling back to "text".') parser.add_argument('-v', '--verbose', action='store_true', help='Enable profiler internal tracing output. Cryptic and verbose.') parser.add_argument('-s', '--statistic', default=0, type=float, help='Use this period for statistic profiling, or use deterministic ' 'profiling when 0.') parser.add_argument('-m', dest='module', help='Searches sys.path for the named module and runs the ' 'corresponding .py file as a script. When given, positional arguments ' 'become sys.argv[1:]') group = parser.add_argument_group( title='Filtering', description='Allows excluding (and re-including) code from ' '"file names" matching regular expressions. ' '"file name" follows the semantics of python\'s "co_filename": ' 'it may be a valid path, of an existing or non-existing file, ' 'but it may be some arbitrary string too.' ) group.add_argument('--exclude-syspath', action='store_true', help='Exclude all from default "sys.path". Beware: this will also ' 'exclude properly-installed non-standard modules, which may not be ' 'what you want.') group.add_argument('--exclude', action='append', default=[], help='Exclude files whose name starts with any pattern.') group.add_argument('--include', action='append', default=[], help='Include files whose name would have otherwise excluded. ' 'If no exclusion was specified, all paths are excluded first.') options = parser.parse_args(argv[1:]) if options.exclude_syspath: options.exclude.extend('^' + re.escape(x) for x in sys.path) if options.include and not options.exclude: options.exclude.append('') # All-matching regex if options.verbose: if options.exclude: print('Excluding:', file=sys.stderr) for regex in options.exclude: print('\t' + regex, file=sys.stderr) if options.include: print('But including:', file=sys.stderr) for regex in options.include: print('\t' + regex, file=sys.stderr) if options.module is None: if options.script is None: parser.error('too few arguments') args = [options.script] + options.argv runner_method_kw = { 'path': args[0], 'argv': args, } runner_method_id = 'runpath' elif stdin is not None and options.module == '-': # Undocumented way of using -m, used internaly by %%pprofile args = [''] if options.script is not None: args.append(options.script) args.extend(options.argv) from . import __main__ runner_method_kw = { 'fd': stdin, 'argv': args, 'fd_name': '', 'globals': __main__.__dict__, } runner_method_id = 'runfile' else: args = [options.module] if options.script is not None: args.append(options.script) args.extend(options.argv) runner_method_kw = { 'module': options.module, 'argv': args, } runner_method_id = 'runmodule' if options.format is None: if os.path.splitext(options.out)[1] == os.path.extsep + 'zip': options.format = 'callgrindzip' elif _isCallgrindName(options.out): options.format = 'callgrind' else: options.format = 'text' relative_path = options.format == 'callgrind' and options.zipfile if options.statistic: prof = StatisticalProfile() runner = StatisticalThread( profiler=prof, period=options.statistic, single=not options.threads, ) else: if options.threads: klass = ThreadProfile else: klass = Profile prof = runner = klass(verbose=options.verbose) try: getattr(runner, runner_method_id)(**runner_method_kw) finally: if options.out == '-': out = EncodeOrReplaceWriter(sys.stdout) close = lambda: None else: if options.format == 'callgrindzip': out = io.open(options.out, 'wb') else: out = io.open(options.out, 'w', errors='replace') close = out.close if options.exclude: exclusion_search_list = [ re.compile(x).search for x in options.exclude ] include_search_list = [ re.compile(x).search for x in options.include ] filename_set = { x for x in prof.getFilenameSet() if not ( any(y(x) for y in exclusion_search_list) and not any(y(x) for y in include_search_list) ) } else: filename_set = None commandline = quoteCommandline(args) getattr(prof, format_dict[options.format])( out, filename=filename_set, # python2 repr returns bytes, python3 repr returns unicode commandline=getattr( commandline, 'decode', lambda _: commandline, )('ascii'), relative_path=relative_path, ) close() zip_path = options.zipfile if zip_path: if relative_path: convertPath = _relpath else: convertPath = lambda x: x with zipfile.ZipFile( zip_path, mode='w', compression=zipfile.ZIP_DEFLATED, ) as zip_file: for name, lines in prof.iterSource(): zip_file.writestr( convertPath(name), ''.join(lines) ) if options.statistic and not runner.clean_exit: # Mostly useful for regresion testing, as exceptions raised in threads # do not change exit status. sys.exit(1) def pprofile(line, cell=None): """ Profile line execution. """ if cell is None: # TODO: detect and use arguments (statistical profiling, ...) ? return run(line) return main( ['%%pprofile', '-m', '-'] + shlex.split(line), io.StringIO(cell), ) try: register_line_cell_magic(pprofile) except Exception: # ipython can be imported, but may not be currently running. pass del pprofile from ._version import get_versions __version__ = get_versions()['version'] del get_versions pprofile-2.1.0/pprofile/__main__.py000066400000000000000000000014661412727544400172650ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2020 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from . import main main() pprofile-2.1.0/pprofile/_version.py000066400000000000000000000441111412727544400173630ustar00rootroot00000000000000 # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = " (HEAD -> master, tag: 2.1.0)" git_full = "4b37c2ee5e61ce2ae2efd50e086d19b4077b8d29" git_date = "2021-10-06 10:32:04 +0000" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "pprofile-" cfg.versionfile_source = "_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} pprofile-2.1.0/pprofile/zope.py000066400000000000000000000516061412727544400165230ustar00rootroot00000000000000# Copyright (C) 2016-2020 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Zope-friendly layer for pprofile. In Zope: - Executed code is not necessarily a valid FS path (ex: Python Scripts) - Executed code is not available to the machine where profiling results are analysed. - Restricted Python cannot manipulate all desired types, and one may want to trigger profiling from its level. This layer addresses all these issues, by making interesting pprofile classes accessible to restricted python and bundling source code wxith profiling results. NOTE: This does allow anyone able to get profiler output to get whole source files from your server. So better keep good track of who can profile and/or where profiling results end. Alone, this module won't be accessible from Restricted Python. Example deterministic usage: # Get profiler (how you get to zpprofile module depends on your # application). profiler = zpprofile.getProfiler() # Get callable (to not profile how it is retrieved). func = context.somethingOrOther # Actually profile stuff with profiler: func() # Build response response = context.REQUEST.RESPONSE data, content_type = profiler.asZip() response.setHeader('content-type', content_type) response.setHeader( 'content-disposition', 'attachment; filename="' + func.id + '.zip"', ) # Push response immediately (hopefully, profiled function did not write # anything on its own). response.write(data) # Make transaction fail, so any otherwise persistent change made by # profiled function is undone - note that many caches will still have # been warmed up, just as with any other code. raise Exception('profiling') Example statistic usage (to profile other running threads): from time import sleep # Get profiler (how you get to zpprofile module depends on your # application). profiler, thread = zpprofile.getStatisticalProfilerAndThread(single=False) # Actually profile whatever is going on in the same process, just waiting. with thread: sleep(60) # Build response response = context.REQUEST.RESPONSE data, content_type = profiler.asZip() response.setHeader('content-type', content_type) response.setHeader( 'content-disposition', 'attachment; filename="statistical_' + DateTime().strftime('%Y%m%d%H%M%S') + '.zip"', ) return data """ from __future__ import print_function import dis import functools import gc from io import StringIO, BytesIO from importlib import import_module import itertools from collections import defaultdict import pprofile if sys.version_info >= (3, ): unicode = str def getFuncCodeOrNone(module, attribute_path): try: value = import_module(module) for attribute in attribute_path: value = getattr(value, attribute) value = value.__code__ except (ImportError, AttributeError): print('Could not reach func_code of module %r, attribute path %r' % (module, attribute_path)) return None return value DB_query_func_code = getFuncCodeOrNone('Products.ZMySQLDA.db', ('DB', '_query')) ZODB_setstate_func_code = getFuncCodeOrNone('ZODB.Connection', ('Connection', '_setstate')) PythonExpr__call__func_code = getFuncCodeOrNone('zope.tales.pythonexpr', ('PythonExpr', '__call__')) ZRPythonExpr__call__func_code = getFuncCodeOrNone('Products.PageTemplates.ZRPythonExpr', ('PythonExpr', '__call__')) DT_UtilEvaleval_func_code = getFuncCodeOrNone('DocumentTemplate.DT_Util', ('Eval', 'eval')) SharedDCScriptsBindings_bindAndExec_func_code = getFuncCodeOrNone('Shared.DC.Scripts.Bindings', ('Bindings', '_bindAndExec')) PythonScript_exec_func_code = getFuncCodeOrNone('Products.PythonScripts.PythonScript', ('PythonScript', '_exec')) # OFS.Traversable.Traversable.unrestrictedTraverse overwites its path argument, # preventing post-invocation introspection. As it does not mutate the argument, # it is still possible to inspect using such controlled intermediate function. def unrestrictedTraverse_spy(self, path, *args, **kw): return orig_unrestrictedTraverse(self, path, *args, **kw) unrestrictedTraverse_spy_func_code = unrestrictedTraverse_spy.__code__ try: import OFS.Traversable orig_unrestrictedTraverse = OFS.Traversable.Traversable.unrestrictedTraverse except (ImportError, AttributeError): pass else: functools.update_wrapper(unrestrictedTraverse_spy, orig_unrestrictedTraverse) OFS.Traversable.Traversable.unrestrictedTraverse = unrestrictedTraverse_spy PYTHON_EXPR_FUNC_CODE_SET = (ZRPythonExpr__call__func_code, PythonExpr__call__func_code) class ZopeFileTiming(pprofile.FileTiming): def call(self, code, line, callee_file_timing, callee, duration, frame): f_code = frame.f_code if f_code is DB_query_func_code: self.profiler.sql_dict[frame.f_locals['query']].append(duration) elif f_code is ZODB_setstate_func_code: f_locals = frame.f_locals obj = f_locals['obj'] try: oid = obj._p_oid except AttributeError: pass else: self.profiler.zodb_dict[ f_locals['self'].db().database_name ][oid].append(duration) elif f_code is unrestrictedTraverse_spy_func_code: f_locals = frame.f_locals self.profiler.traverse_dict[ (repr(f_locals['self']), repr(f_locals['path'])) ].append(duration) super(ZopeFileTiming, self).call( code, line, callee_file_timing, callee, duration, frame, ) def tabulate(title_list, row_list): # de-lazify row_list = list(row_list) column_count = len(title_list) max_width_list = [len(x) for x in title_list] for row in row_list: assert len(row) == column_count, repr(row) for index, value in enumerate(row): max_width_list[index] = max(max_width_list[index], len(unicode(value))) format_string = u''.join(u'| %%-%is ' % x for x in max_width_list) + u'|\n' out = StringIO() write = out.write write(format_string % tuple(title_list)) write(u''.join(u'+' + (u'-' * (x + 2)) for x in max_width_list) + u'+\n') for row in row_list: write(format_string % tuple(row)) return out.getvalue() def disassemble(co, lasti=-1): """Disassemble a code object.""" # Taken from dis.disassemble, returns disassembled code instead of printing # it (the fuck python ?). # Also, unicodified. # Also, use % operator instead of string operations. # Also, one statement per line. out = StringIO() code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i in linestarts: if i > 0: print(end=u'\n', file=out) print(u'%3d' % linestarts[i], end=u' ', file=out) else: print(u' ', end=u' ', file=out) if i == lasti: print(u'-->', end=u' ', file=out) else: print(u' ', end=u' ', file=out) if i in labels: print(u'>>', end=u' ', file=out) else: print(u' ', end=u' ', file=out) print(u'%4i' % i, end=u' ', file=out) print(u'%-20s' % dis.opname[op], end=u' ', file=out) i = i + 1 if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg extended_arg = 0 i = i + 2 if op == dis.EXTENDED_ARG: extended_arg = oparg * 65536 print(u'%5i' % oparg, end=u' ', file=out) if op in dis.hasconst: print(u'(%r)' % co.co_consts[oparg], end=u' ', file=out) elif op in dis.hasname: print(u'(%s)' % co.co_names[oparg], end=u' ', file=out) elif op in dis.hasjrel: print(u'(to %r)' % (i + oparg), end=u' ', file=out) elif op in dis.haslocal: print(u'(%s)' % co.co_varnames[oparg], end=u' ', file=out) elif op in dis.hascompare: print(u'(%s)' % dis.cmp_op[oparg], end=u' ', file=out) elif op in dis.hasfree: if free is None: free = co.co_cellvars + co.co_freevars print(u'(%s)' % free[oparg], end=u' ', file=out) print(end=u'\n', file=out) return out.getvalue() class ZopeMixIn(object): virtual__slots__ = ( 'sql_dict', 'zodb_dict', 'fake_source_dict', 'traverse_dict', 'keep_alive', # until they see the cake ) __allow_access_to_unprotected_subobjects__ = 1 FileTiming = ZopeFileTiming def __init__(self): super(ZopeMixIn, self).__init__() self.sql_dict = defaultdict(list) self.zodb_dict = defaultdict(lambda: defaultdict(list)) self.fake_source_dict = {} self.traverse_dict = defaultdict(list) self.keep_alive = [] def _enable(self): gc.disable() super(ZopeMixIn, self)._enable() def _disable(self): super(ZopeMixIn, self)._disable() gc.enable() def _getline(self, filename, lineno, global_dict): line_list = self.fake_source_dict.get(filename) if line_list is None: return super(ZopeMixIn, self)._getline( filename, lineno, global_dict, ) assert lineno > 0 try: return line_list[lineno - 1] except IndexError: return '' def _rememberFile(self, source, suggested_name, extension): filename = suggested_name setdefault = self.fake_source_dict.setdefault suffix = itertools.count() source = source.splitlines(True) while setdefault(filename + extension, source) != source: filename = suggested_name + '_%i' % next(suffix) return filename + extension def _getFileTiming(self, frame): try: return self.global_dict[id(frame.f_globals)] except KeyError: frame_globals = frame.f_globals evaluator_frame = frame.f_back while evaluator_frame is not None: evaluator_code = evaluator_frame.f_code if ( evaluator_code is PythonScript_exec_func_code and evaluator_frame.f_locals.get('g') is frame_globals ): evaluated_module_unique = evaluator_frame.f_locals['fcode'] break elif ( evaluator_code is DT_UtilEvaleval_func_code and evaluator_frame.f_locals.get('d') is frame_globals ): evaluated_module_unique = evaluator_frame.f_locals['code'] break elif ( evaluator_code in PYTHON_EXPR_FUNC_CODE_SET and evaluator_frame.f_locals.get('vars') is frame_globals ): evaluated_module_unique = evaluator_frame.f_locals[ 'self' ]._code break evaluator_frame = evaluator_frame.f_back else: # No evaluator found evaluator_frame = frame evaluated_module_unique = frame_globals try: file_timing = self.global_dict[id(evaluated_module_unique)] except KeyError: # Unknown module, guess its name. if evaluator_frame is frame: # No evaluator found. # The answer was not in the stack. # Maybe its name is actually fine ? name = self._getFilename(frame) if not super(ZopeMixIn, self)._getline( name, 1, frame.f_globals, ): # Shared.DC.Scripts preamble is directly called by # _bindAndExec. if getattr( frame.f_back, 'f_code', None, ) is SharedDCScriptsBindings_bindAndExec_func_code: name = self._rememberFile( u'# This is an auto-generated preamble executed ' u'by Shared.DC.Scripts.Bindings before "actual" ' u'code.\n' + disassemble(frame.f_code), 'preamble', '.py.bytecode', ) else: # Could not find source, provide disassembled # bytecode as last resort. name = self._rememberFile( u'# Unidentified source for ' + name + '\n' + disassemble( frame.f_code, ), '%s.%s' % (name, frame.f_code.co_name), '.py.bytecode', ) else: # Evaluator found. if evaluator_code is PythonScript_exec_func_code: python_script = evaluator_frame.f_locals['self'] name = self._rememberFile( python_script.body().decode('utf-8'), python_script.id, '.py', ) elif evaluator_code is DT_UtilEvaleval_func_code: name = self._rememberFile( evaluator_frame.f_locals['self'].expr.decode( 'utf-8', ), 'DT_Util_Eval', '.py', ) elif evaluator_code in PYTHON_EXPR_FUNC_CODE_SET: source = evaluator_frame.f_locals['self'].text if not isinstance(source, unicode): source = source.decode('utf-8') name = self._rememberFile( source, 'PythonExpr', '.py', ) else: raise ValueError(evaluator_code) self.keep_alive.append(evaluated_module_unique) # Create FileTiming and store as module... self.global_dict[ id(evaluated_module_unique) ] = file_timing = self.FileTiming( name, frame_globals, self, ) # ...and for later deduplication (in case of multithreading). # file_dict modifications must be thread-safe to not lose # measures. setdefault is atomic, append is atomic. self.file_dict.setdefault(name, []).append(file_timing) # Alias module FileTiming to current globals, for faster future # lookup. self.global_dict[id(frame_globals)] = file_timing self.keep_alive.append(frame_globals) return file_timing def _iterOutFiles(self, *args, **kw): """ Yields path, data, mimetype for each file involved on or produced by profiling. """ for entry in super(ZopeMixIn, self)._iterOutFiles(*args, **kw): yield entry sql_name_template = 'query_%%0%ii-%%i_hits_%%6fs.sql' % len( str(len(self.sql_dict)), ) for index, (query, time_list) in enumerate( sorted( self.sql_dict.items(), key=lambda x: (sum(x[1]), len(x[1])), reverse=True, ), ): yield ( sql_name_template % ( index, len(time_list), sum(time_list), ), b'\n'.join(b'-- %10.6fs' % x for x in time_list) + b'\n' + query, 'application/sql', ) if self.zodb_dict: yield ( 'ZODB_setstate.txt', '\n\n'.join( ( '%s (%fs)\n' % ( db_name, sum(sum(x) for x in oid_dict.values()), ) ) + '\n'.join( '%s (%i): %s' % ( oid.encode('hex'), len(time_list), ', '.join('%fs' % x for x in time_list), ) for oid, time_list in oid_dict.items() ) for db_name, oid_dict in self.zodb_dict.items() ), 'text/plain', ) if self.traverse_dict: yield ( 'unrestrictedTraverse_pathlist.txt', tabulate( ('self', 'path', 'hit', 'total duration'), sorted( ( (context, path, len(duration_list), sum(duration_list)) for (context, path), duration_list in self.traverse_dict.items() ), key=lambda x: x[3], reverse=True, ), ), 'text/plain', ) def getCallgrindMIME(self): """ Return a mime-multipart representation of: - callgrind profiling statistics (cachegrind.out.pprofile) - any SQL query issued via ZMySQLDA (query_*.sql) - any persistent object load via ZODB.Connection (ZODB_setstate.txt) - any path argument given to unrestrictedTraverse (unrestrictedTraverse_pathlist.txt) - all involved python code, including Python Scripts without hierarchy (the rest) and the mimetype of this string. To unpack resulting file, see "unpack a MIME message" in http://docs.python.org/2/library/email-examples.html Or get demultipart from https://pypi.python.org/pypi/demultipart """ out = BytesIO() mimetype = super(ZopeMixIn, self).getCallgrindMIME(out) return out.getvalue(), mimetype def getCallgrindZip(self): """ Return a serialised zip archive containing: - callgrind profiling statistics (cachegrind.out.pprofile) - any SQL query issued via ZMySQLDA (query_*.sql) - any persistent object load via ZODB.Connection (ZODB_setstate.txt) - any path argument given to unrestrictedTraverse (unrestrictedTraverse_pathlist.txt) - all involved python code, including Python Scripts without hierarchy (the rest) and the "application/zip" mimetype. """ out = BytesIO() mimetype = super(ZopeMixIn, self).getCallgrindZip(out) return out.getvalue(), mimetype # BBB asMIMEString = getCallgrindMIME asZip = getCallgrindZip class ZopeProfiler(ZopeMixIn, pprofile.Profile): __slots__ = ZopeMixIn.virtual__slots__ class ZopeStatisticalProfile(ZopeMixIn, pprofile.StatisticalProfile): __slots__ = ZopeMixIn.virtual__slots__ class ZopeStatisticalThread(pprofile.StatisticalThread): __allow_access_to_unprotected_subobjects__ = 1 # Intercept "verbose" parameter to prevent writing to stdout. def getProfiler(verbose=False, **kw): """ Get a Zope-friendly pprofile.Profile instance. """ return ZopeProfiler(**kw) def getStatisticalProfilerAndThread(**kw): """ Get Zope-friendly pprofile.StatisticalProfile and pprofile.StatisticalThread instances. Arguments are forwarded to StatisticalThread.__init__ . """ profiler = ZopeStatisticalProfile() return profiler, ZopeStatisticalThread( profiler=profiler, **kw ) pprofile-2.1.0/setup.cfg000066400000000000000000000002431412727544400151640ustar00rootroot00000000000000[versioneer] VCS = git style = pep440 versionfile_source = pprofile/_version.py versionfile_build = pprofile/_version.py tag_prefix = parentdir_prefix = pprofile- pprofile-2.1.0/setup.py000066400000000000000000000040531412727544400150600ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2013-2020 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from os.path import join, dirname import sys from setuptools import setup import versioneer description = open(join(dirname(__file__), 'README.rst')).read() setup( name='pprofile', version=versioneer.get_version(), author='Vincent Pelletier', author_email='plr.vincent@gmail.com', description=next(x for x in description.splitlines() if x.strip()), long_description='.. contents::\n\n' + description, url='http://github.com/vpelletier/pprofile', license='GPL 2+', platforms=['any'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: PyPy', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: IronPython', 'Topic :: Software Development', ], packages=['pprofile'], py_modules=['zpprofile'], entry_points={ 'console_scripts': [ 'pprofile=pprofile:main', ], }, zip_safe=True, cmdclass=versioneer.get_cmdclass(), ) pprofile-2.1.0/test.sh000077500000000000000000000037531412727544400146720ustar00rootroot00000000000000#!/bin/sh set -eu repository="$(dirname "$0")" cd "$repository" for python in /usr/bin/python /usr/bin/python3 /usr/bin/pypy3; do echo "Testing with $python" testdir="$(mktemp --tmpdir --directory "pprofile_tests.XXXXXXXX")" trap 'rm -r "$testdir"' EXIT virtualenv -p "$python" "$testdir" "${testdir}/bin/pip" install "$repository" pprofile="${testdir}/bin/pprofile" "$pprofile" --include demo --threads 0 demo/threads.py "$pprofile" --include demo --format callgrind demo/threads.py "$pprofile" --include demo --statistic .01 demo/threads.py "${testdir}/bin/python" demo/embedded.py "$pprofile" --include demo demo/threads.py "$pprofile" --include demo demo/empty.py "$pprofile" --format callgrind demo/empty.py "$pprofile" --include demo --statistic .01 demo/empty.py "$pprofile" --format callgrind --zipfile "${testdir}/source_code.zip" demo/threads.py "$pprofile" --format callgrind --zipfile "${testdir}/source_code.zip" demo/empty.py "$pprofile" --exclude-syspath demo/threads.py "$pprofile" --exclude-syspath --statistic .01 demo/threads.py "$pprofile" --include demo demo/encoding.py LC_CTYPE=ISO-8859-15 "$pprofile" --include demo demo/encoding.py "$pprofile" --include demo demo/encoding.py > /dev/null "$pprofile" --include demo demo/empty.py -search "$pprofile" --include demo -- demo/empty.py -search "$pprofile" --include demo demo/recurse.py "$pprofile" --include demo demo/recurse2.py "$pprofile" --include demo demo/recurse3.py "$pprofile" --include demo demo/recurse4.py "$pprofile" --include demo demo/twocalls.py "$pprofile" --include demo demo/twocalls2.py "$pprofile" --include demo demo/the_main.py "$pprofile" --include demo demo/module_globals.py "$pprofile" --format callgrindzip --out "${testdir}/test_threads.zip" demo/threads.py && unzip -l "${testdir}/test_threads.zip" "$pprofile" --out "${testdir}/test_threads.zip" demo/threads.py && unzip -l "${testdir}/test_threads.zip" trap - EXIT rm -r "$testdir" done echo 'Success' pprofile-2.1.0/versioneer.py000066400000000000000000002060031412727544400161000ustar00rootroot00000000000000 # Version: 0.18 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other langauges) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1) pprofile-2.1.0/zpprofile.py000066400000000000000000000000341412727544400157250ustar00rootroot00000000000000from pprofile.zope import *