hupper-1.0/0000755000076500000240000000000013107411503013375 5ustar michaelstaff00000000000000hupper-1.0/.coveragerc0000644000076500000240000000027413104764343015533 0ustar michaelstaff00000000000000[run] parallel = true source = hupper tests omit = src/hupper/winapi.py [paths] source = src/hupper */site-packages/hupper [report] show_missing = true precision = 2 hupper-1.0/.travis.yml0000644000076500000240000000075413105251443015517 0ustar michaelstaff00000000000000sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: include: - python: '3.6' env: TOXENV=py36 - python: '3.5' env: TOXENV=py35 - python: '3.4' env: TOXENV=py34 - python: '2.7' env: TOXENV=py27 - python: 'pypy' env: TOXENV=pypy - python: '3.6' env: TOXENV=py2,py3,coverage - python: '3.6' env: TOXENV=docs - python: '3.6' env: TOXENV=pep8 install: pip install tox script: tox hupper-1.0/appveyor.yml0000644000076500000240000000101013041606563015766 0ustar michaelstaff00000000000000environment: matrix: - PYTHON: "C:\\Python36" TOXENV: "py36" - PYTHON: "C:\\Python35" TOXENV: "py35" - PYTHON: "C:\\Python27" TOXENV: "py27" - PYTHON: "C:\\Python36-x64" TOXENV: "py36" - PYTHON: "C:\\Python35-x64" TOXENV: "py35" - PYTHON: "C:\\Python27-x64" TOXENV: "py27" cache: - '%LOCALAPPDATA%\pip\Cache' version: '{branch}.{build}' install: - "%PYTHON%\\python.exe -m pip install tox" build: off test_script: - "%PYTHON%\\Scripts\\tox.exe" hupper-1.0/CHANGES.rst0000644000076500000240000000765013107400327015211 0ustar michaelstaff000000000000001.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. hupper-1.0/CONTRIBUTING.rst0000644000076500000240000000561713001324705016047 0ustar michaelstaff00000000000000.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/Pylons/hupper/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ hupper could always use more documentation, whether as part of the official hupper docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/Pylons/hupper/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `hupper` for local development. 1. Fork the `hupper` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/hupper.git 3. Install your local copy into a virtualenv:: $ python3 -m venv env $ env/bin/pip install -e .[docs,testing] $ env/bin/pip install tox 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ env/bin/tox 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.7, 3.4 and 3.5, and for PyPy. Check https://travis-ci.org/Pylons/hupper/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ env/bin/py.test tests.test_hupper hupper-1.0/docs/0000755000076500000240000000000013107411503014325 5ustar michaelstaff00000000000000hupper-1.0/docs/_static/0000755000076500000240000000000013107411503015753 5ustar michaelstaff00000000000000hupper-1.0/docs/_static/.keep0000644000076500000240000000000013002321523016662 0ustar michaelstaff00000000000000hupper-1.0/docs/api.rst0000644000076500000240000000131113007475462015641 0ustar michaelstaff00000000000000================== :mod:`hupper` API ================== .. automodule:: hupper .. autofunction:: start_reloader .. autofunction:: is_active .. autofunction:: get_reloader .. autofunction:: is_watchdog_supported .. automodule:: hupper.reloader .. autoclass:: Reloader :members: .. automodule:: hupper.interfaces .. autoclass:: IReloaderProxy :members: :special-members: .. autoclass:: IFileMonitor :members: :special-members: .. autoclass:: IFileMonitorFactory :members: :special-members: .. automodule:: hupper.polling .. autoclass:: PollingFileMonitor :members: .. automodule:: hupper.watchdog .. autoclass:: WatchdogFileMonitor :members: hupper-1.0/docs/changes.rst0000644000076500000240000000006513001322512016462 0ustar michaelstaff00000000000000======= Changes ======= .. include:: ../CHANGES.rst hupper-1.0/docs/conf.py0000644000076500000240000002027313055465702015644 0ustar michaelstaff00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # hupper documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import pkg_resources # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) # ensure the code is importable for use with autodoc import hupper # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'hupper' copyright = u'2017, Michael Merickel' # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = pkg_resources.get_distribution('hupper').version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built # documents. #keep_warnings = False # -- Options for HTML output ------------------------------------------- # Add and use Pylons theme sys.path.append(os.path.abspath('_themes')) import pylons_sphinx_themes html_theme_path = pylons_sphinx_themes.get_html_themes_path() html_theme = 'pylons' html_theme_options = { 'github_url': 'https://github.com/Pylons/pyramid_jinja2' } # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. # Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. # Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages # will contain a tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'hupperdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'hupper.tex', u'hupper Documentation', u'Michael Merickel', 'manual'), ] # The name of an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'hupper', u'hupper Documentation', [u'Michael Merickel'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'hupper', u'hupper Documentation', u'Michael Merickel', 'hupper', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False hupper-1.0/docs/contributing.rst0000644000076500000240000000004113001322512017553 0ustar michaelstaff00000000000000.. include:: ../CONTRIBUTING.rst hupper-1.0/docs/index.rst0000644000076500000240000000721713032633125016200 0ustar michaelstaff00000000000000====== hupper ====== ``hupper`` is monitor for your Python process. When files change, the process will be restarted. It can be extended to watch arbitrary files. Reloads can also be triggered manually from code. File monitoring can be done using basic polling or using inotify-style filesystem events if watchdog_ is installed. Installation ============ Stable release -------------- To install hupper, run this command in your terminal: .. code-block:: console $ pip install hupper If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for hupper can be downloaded from the `Github repo`_. .. code-block:: console $ git clone https://github.com/Pylons/hupper.git Once you have a copy of the source, you can install it with: .. code-block:: console $ pip install -e . .. _Github repo: https://github.com/Pylons/hupper Watchdog support ---------------- If `watchdog `_ is installed, it will be used to more efficiently watch for changes to files. .. code-block:: console $ pip install watchdog This is an optional dependency and if it's not installed, then ``hupper`` will fallback to less efficient polling of the filesystem. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= The reloading mechanism is implemented by forking worker processes from a parent monitor. Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``: .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain']) yield [b'hello'] def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Many applications will tend to re-use the same startup code for both the monitor and the worker. As a convenience to support this use case, the :func:`hupper.start_reloader` function can be invoked both from the parent process as well as the worker. When called initially from the parent process, it will fork a new worker, then start the monitor and never return. When called from the worker process it will return a proxy object that can be used to communicate back to the monitor. Checking if the reloader is active ---------------------------------- :func:`hupper.is_active` will return ``True`` if the reloader is active and the current process may be reloaded. Controlling the monitor ----------------------- The worker processes may communicate back to the monitor and notify it of new files to watch. This can be done by acquiring a reference to the :class:`hupper.interfaces.IReloaderProxy` instance living in the worker process. The :func:`hupper.start_reloader` function will return the instance or :func:`hupper.get_reloader` can be used as well. More Information ================ .. toctree:: :maxdepth: 1 api contributing changes Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` hupper-1.0/docs/make.bat0000644000076500000240000001447313001340166015742 0ustar michaelstaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\hupper.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\hupper.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end hupper-1.0/docs/Makefile0000644000076500000240000001515213001340151015762 0ustar michaelstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/hupper.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/hupper.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/hupper" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/hupper" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." hupper-1.0/LICENSE.txt0000644000076500000240000000204413032627326015231 0ustar michaelstaff00000000000000Copyright (c) 2017 Michael Merickel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. hupper-1.0/MANIFEST.in0000644000076500000240000000034713014151356015143 0ustar michaelstaff00000000000000graft src graft tests graft docs include README.rst include CHANGES.rst include LICENSE.txt include CONTRIBUTING.rst include .coveragerc include tox.ini appveyor.yml .travis.yml rtd.txt recursive-exclude * __pycache__ *.py[cod] hupper-1.0/PKG-INFO0000644000076500000240000002042113107411503014471 0ustar michaelstaff00000000000000Metadata-Version: 1.2 Name: hupper Version: 1.0 Summary: Integrated process monitor for developing and reloading daemons. Home-page: https://github.com/Pylons/hupper Author: Michael Merickel Author-email: pylons-discuss@googlegroups.com License: MIT Description: ====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain']) yield [b'hello'] def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. 1.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. Keywords: server daemon autoreload reloader hup file watch process Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* hupper-1.0/README.rst0000644000076500000240000000347713067122354015107 0ustar michaelstaff00000000000000====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain']) yield [b'hello'] def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. hupper-1.0/rtd.txt0000644000076500000240000000001313002320710014712 0ustar michaelstaff00000000000000-e .[docs] hupper-1.0/setup.cfg0000644000076500000240000000037413107411503015222 0ustar michaelstaff00000000000000[wheel] universal = 1 [metadata] license_file = LICENSE.txt [flake8] exclude = hupper/compat.py, show-source = True max-line-length = 80 [tool:pytest] python_files = test_*.py testpaths = src/hupper tests [egg_info] tag_build = tag_date = 0 hupper-1.0/setup.py0000644000076500000240000000333013107400271015106 0ustar michaelstaff00000000000000from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') docs_require = [ 'watchdog', 'Sphinx', 'pylons-sphinx-themes', ] tests_require = [ 'watchdog', 'pytest', 'pytest-cov', 'mock', ] setup( name='hupper', version='1.0', description=( 'Integrated process monitor for developing and reloading daemons.' ), long_description=readme + '\n\n' + changes, author='Michael Merickel', author_email='pylons-discuss@googlegroups.com', url='https://github.com/Pylons/hupper', license='MIT', packages=find_packages('src', exclude=['tests']), package_dir={'': 'src'}, include_package_data=True, python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', extras_require={ 'docs': docs_require, 'testing': tests_require, }, entry_points={"console_scripts": ["hupper = hupper.cli:main"]}, zip_safe=False, keywords='server daemon autoreload reloader hup file watch process', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], ) hupper-1.0/src/0000755000076500000240000000000013107411503014164 5ustar michaelstaff00000000000000hupper-1.0/src/hupper/0000755000076500000240000000000013107411503015467 5ustar michaelstaff00000000000000hupper-1.0/src/hupper/__init__.py0000644000076500000240000000025713011246730017606 0ustar michaelstaff00000000000000# public api # flake8: noqa from .compat import is_watchdog_supported from .reloader import ( start_reloader, ) from .worker import ( is_active, get_reloader, ) hupper-1.0/src/hupper/cli.py0000644000076500000240000000074013032610727016617 0ustar michaelstaff00000000000000from __future__ import print_function import argparse import sys from .reloader import start_reloader def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", dest="module", required=True) args, unknown_args = parser.parse_known_args() sys.argv[1:] = unknown_args sys.path.insert(0, "") start_reloader( "runpy.run_module", worker_args=[args.module], worker_kwargs={"alter_sys": True, "run_name": "__main__"}) hupper-1.0/src/hupper/compat.py0000644000076500000240000000226713105251110017325 0ustar michaelstaff00000000000000# flake8: noqa import imp import importlib import sys PY2 = sys.version_info[0] == 2 WIN = sys.platform == 'win32' try: import queue except ImportError: import Queue as queue try: from _thread import interrupt_main except ImportError: from thread import interrupt_main try: from importlib.util import ( cache_from_source as get_pyc_path, source_from_cache as get_py_path, ) except ImportError: if PY2: get_pyc_path = lambda path: path + 'c' get_py_path = lambda path: path[:-1] # fallback on python < 3.5 else: get_pyc_path = imp.cache_from_source get_py_path = imp.source_from_cache try: import cPickle as pickle except ImportError: import pickle def is_watchdog_supported(): """ Return ``True`` if watchdog is available.""" try: import watchdog except ImportError: return False return True ################################################ # cross-compatible metaclass implementation # Copyright (c) 2010-2012 Benjamin Peterson def with_metaclass(meta, base=object): """Create a base class with a metaclass.""" return meta("%sBase" % meta.__name__, (base,), {}) hupper-1.0/src/hupper/interfaces.py0000644000076500000240000000226113011246730020167 0ustar michaelstaff00000000000000import abc from .compat import with_metaclass class IReloaderProxy(with_metaclass(abc.ABCMeta)): @abc.abstractmethod def watch_files(self, files): """ Signal to the monitor to track some custom paths.""" @abc.abstractmethod def trigger_reload(self): """ Signal the monitor to execute a reload.""" class IFileMonitorFactory(with_metaclass(abc.ABCMeta)): def __call__(self, callback): """ Return an :class:`.IFileMonitor` instance. ``callback`` is a callable to be invoked by the ``IFileMonitor`` when file changes are detected. It should accept the path of the changed file as its only parameter. """ class IFileMonitor(with_metaclass(abc.ABCMeta)): @abc.abstractmethod def add_path(self, path): """ Start monitoring a new path.""" @abc.abstractmethod def start(self): """ Start the monitor. This method should not block.""" @abc.abstractmethod def stop(self): """ Trigger the monitor to stop. This should be called before invoking :meth:`.join`. """ @abc.abstractmethod def join(self): """ Block until the monitor has stopped.""" hupper-1.0/src/hupper/ipc.py0000644000076500000240000002072113107400104016611 0ustar michaelstaff00000000000000import io import imp import importlib import os import struct import sys import subprocess import threading from .compat import WIN from .compat import pickle from .compat import queue def resolve_spec(spec): modname, funcname = spec.rsplit('.', 1) module = importlib.import_module(modname) func = getattr(module, funcname) return func if WIN: # pragma: no cover import msvcrt from . import winapi class ProcessGroup(object): def __init__(self): self.h_job = winapi.CreateJobObject(None, None) info = winapi.JOBOBJECT_BASIC_LIMIT_INFORMATION() info.LimitFlags = winapi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE extended_info = winapi.JOBOBJECT_EXTENDED_LIMIT_INFORMATION() extended_info.BasicLimitInformation = info winapi.SetInformationJobObject( self.h_job, winapi.JobObjectExtendedLimitInformation, extended_info, ) def add_child(self, pid): hp = winapi.OpenProcess(winapi.PROCESS_ALL_ACCESS, False, pid) try: return winapi.AssignProcessToJobObject(self.h_job, hp) except OSError as ex: if getattr(ex, 'winerror') == 5: # skip ACCESS_DENIED_ERROR on windows < 8 which occurs when # the process is already attached to another job pass else: raise def snapshot_termios(fd): pass def restore_termios(fd, state): pass def get_handle(fd): return msvcrt.get_osfhandle(fd) def open_handle(handle, mode): flags = 0 if 'w' not in mode and '+' not in mode: flags |= os.O_RDONLY if 'b' not in mode: flags |= os.O_TEXT if 'a' in mode: flags |= os.O_APPEND return msvcrt.open_osfhandle(handle, flags) else: import fcntl import termios class ProcessGroup(object): def add_child(self, pid): # nothing to do on *nix pass def snapshot_termios(fd): if os.isatty(fd): state = termios.tcgetattr(fd) return state def restore_termios(fd, state): if os.isatty(fd) and state: termios.tcflush(fd, termios.TCIOFLUSH) termios.tcsetattr(fd, termios.TCSANOW, state) def get_handle(fd): return fd def open_handle(handle, mode): return handle def _pipe(): r, w = os.pipe() set_inheritable(r, False) set_inheritable(w, False) return r, w def Pipe(): c2pr_fd, c2pw_fd = _pipe() p2cr_fd, p2cw_fd = _pipe() c1 = Connection(c2pr_fd, p2cw_fd) c2 = Connection(p2cr_fd, c2pw_fd) return c1, c2 class Connection(object): """ A connection to a bi-directional pipe. """ _packet_len = struct.Struct('Q') def __init__(self, r_fd, w_fd): self.r_fd = r_fd self.w_fd = w_fd def __getstate__(self): return { 'r_handle': get_handle(self.r_fd), 'w_handle': get_handle(self.w_fd), } def __setstate__(self, state): self.r_fd = open_handle(state['r_handle'], 'rb') self.w_fd = open_handle(state['w_handle'], 'wb') def activate(self): self.send_lock = threading.Lock() self.reader_queue = queue.Queue() self.reader_thread = threading.Thread(target=self._read_loop) self.reader_thread.daemon = True self.reader_thread.start() def close(self): close_fd(self.r_fd) close_fd(self.w_fd) def _recv_packet(self): buf = io.BytesIO() chunk = os.read(self.r_fd, self._packet_len.size) if not chunk: return size = remaining = self._packet_len.unpack(chunk)[0] while remaining > 0: chunk = os.read(self.r_fd, remaining) n = len(chunk) if n == 0: if remaining == size: raise EOFError else: raise IOError('got end of file during message') buf.write(chunk) remaining -= n return pickle.loads(buf.getvalue()) def _read_loop(self): try: while True: packet = self._recv_packet() if packet is None: break self.reader_queue.put(packet) except EOFError: pass self.reader_queue.put(None) def _write_packet(self, data): while data: n = os.write(self.w_fd, data) data = data[n:] def send(self, value): data = pickle.dumps(value) with self.send_lock: self._write_packet(self._packet_len.pack(len(data))) self._write_packet(data) return len(data) + self._packet_len.size def recv(self, timeout=None): packet = self.reader_queue.get(block=True, timeout=timeout) return packet def set_inheritable(fd, inheritable): # On py34+ we can use os.set_inheritable but < py34 we must polyfill # with fcntl and SetHandleInformation if hasattr(os, 'get_inheritable'): if os.get_inheritable(fd) != inheritable: os.set_inheritable(fd, inheritable) elif WIN: h = get_handle(fd) flags = winapi.HANDLE_FLAG_INHERIT if inheritable else 0 winapi.SetHandleInformation(h, winapi.HANDLE_FLAG_INHERIT, flags) else: flags = fcntl.fcntl(fd, fcntl.F_GETFD) if inheritable: new_flags = flags & ~fcntl.FD_CLOEXEC else: new_flags = flags | fcntl.FD_CLOEXEC if new_flags != flags: fcntl.fcntl(fd, fcntl.F_SETFD, new_flags) def close_fd(fd, raises=True): if fd is not None: try: os.close(fd) except Exception: # pragma: nocover if raises: raise def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args def get_command_line(**kwds): prog = 'from hupper.ipc import spawn_main; spawn_main(%s)' prog %= ', '.join('%s=%r' % item for item in kwds.items()) opts = args_from_interpreter_flags() args = [sys.executable] + opts + ['-c', prog] # ensure hupper is on the PYTHONPATH in the worker process self_path = os.path.abspath(imp.find_module('hupper')[1]) extra_py_paths = [os.path.dirname(self_path)] env = os.environ.copy() env['PYTHONPATH'] = ( os.pathsep.join(extra_py_paths) + os.pathsep + env.get('PYTHONPATH', '') ) return args, env def get_preparation_data(): data = {} data['sys.argv'] = sys.argv # multiprocessing does some work here to replace '' in sys.path with # os.getcwd() but it is not valid to assume that os.getcwd() at the time # hupper is imported is the starting folder of the process so for now # we'll just assume that the user has not changed the CWD data['sys.path'] = list(sys.path) return data def prepare(data): if 'sys.argv' in data: sys.argv = data['sys.argv'] if 'sys.path' in data: sys.path = data['sys.path'] def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process def spawn_main(pipe_handle): fd = open_handle(pipe_handle, 'rb') from_parent = os.fdopen(fd, 'rb') preparation_data, spec, kwargs = pickle.load(from_parent) from_parent.close() prepare(preparation_data) func = resolve_spec(spec) func(**kwargs) sys.exit(0) hupper-1.0/src/hupper/polling.py0000644000076500000240000000322613032645324017517 0ustar michaelstaff00000000000000import os import threading import time from .interfaces import IFileMonitor class PollingFileMonitor(threading.Thread, IFileMonitor): """ An :class:`hupper.interfaces.IFileMonitor` that stats the files at periodic intervals. ``callback`` is a callable that accepts a path to a changed file. ``poll_interval`` is a value in seconds between scans of the files on disk. Do not set this too low or it will eat your CPU and kill your drive. """ def __init__(self, callback, poll_interval=1): super(PollingFileMonitor, self).__init__() self.callback = callback self.poll_interval = poll_interval self.paths = set() self.mtimes = {} self.lock = threading.Lock() def add_path(self, path): with self.lock: self.paths.add(path) def run(self): self.enabled = True while self.enabled: with self.lock: paths = list(self.paths) self.check_reload(paths) time.sleep(self.poll_interval) def stop(self): self.enabled = False def check_reload(self, paths): changes = set() for path in paths: mtime = get_mtime(path) if path not in self.mtimes: self.mtimes[path] = mtime elif self.mtimes[path] < mtime: self.mtimes[path] = mtime changes.add(path) for path in sorted(changes): self.callback(path) def get_mtime(path): try: stat = os.stat(path) if stat: return stat.st_mtime except (OSError, IOError): # pragma: no cover pass return 0 hupper-1.0/src/hupper/reloader.py0000644000076500000240000002041413104736376017656 0ustar michaelstaff00000000000000from __future__ import print_function from glob import glob import signal import sys import threading import time from .compat import is_watchdog_supported from .compat import queue from .ipc import ProcessGroup from .worker import ( Worker, is_active, get_reloader, ) class FileMonitorProxy(object): """ Wrap an :class:`hupper.interfaces.IFileMonitor` into an object that exposes a thread-safe interface back to the reloader to detect when it should reload. """ def __init__(self, monitor_factory, verbose=1): self.monitor = monitor_factory(self.file_changed) self.verbose = verbose self.change_event = threading.Event() self.changed_paths = set() def out(self, msg): if self.verbose > 0: print(msg) def add_path(self, path): # if the glob does not match any files then go ahead and pass # the pattern to the monitor anyway incase it is just a file that # is currently missing for p in glob(path) or [path]: self.monitor.add_path(p) def start(self): self.monitor.start() def stop(self): self.monitor.stop() self.monitor.join() def file_changed(self, path): if path not in self.changed_paths: self.changed_paths.add(path) self.out('%s changed; reloading ...' % (path,)) self.set_changed() def is_changed(self): return self.change_event.is_set() def wait_for_change(self, timeout=None): return self.change_event.wait(timeout) def clear_changes(self): self.change_event.clear() self.changed_paths.clear() def set_changed(self): self.change_event.set() class Reloader(object): """ A wrapper class around a file monitor which will handle changes by restarting a new worker process. """ def __init__(self, worker_path, monitor_factory, reload_interval=1, verbose=1, worker_args=None, worker_kwargs=None, ): self.worker_path = worker_path self.worker_args = worker_args self.worker_kwargs = worker_kwargs self.monitor_factory = monitor_factory self.reload_interval = reload_interval self.verbose = verbose self.monitor = None self.worker = None self.group = ProcessGroup() def out(self, msg): if self.verbose > 0: print(msg) def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1) def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals() def _run_worker(self): self.worker = Worker( self.worker_path, args=self.worker_args, kwargs=self.worker_kwargs, ) self.worker.start() try: # register the worker with the process group self.group.add_child(self.worker.pid) self.out("Starting monitor for PID %s." % self.worker.pid) self.monitor.clear_changes() while not self.monitor.is_changed() and self.worker.is_alive(): try: cmd = self.worker.pipe.recv(timeout=self.reload_interval) except queue.Empty: continue if not cmd or cmd[0] == 'reload': break if cmd[0] == 'watch': for path in cmd[1]: self.monitor.add_path(path) else: raise RuntimeError('received unknown command') except KeyboardInterrupt: if self.worker.is_alive(): self.out('Waiting for server to exit ...') time.sleep(self.reload_interval) raise finally: if self.worker.is_alive(): self.out('Killing server with PID %s.' % self.worker.pid) self.worker.terminate() self.worker.join() else: self.worker.join() self.out('Server with PID %s exited with code %d.' % (self.worker.pid, self.worker.exitcode)) self.monitor.clear_changes() force_restart = self.worker.terminated self.worker = None return force_restart def _wait_for_changes(self): self.out('Waiting for changes before reloading.') while ( not self.monitor.wait_for_change(self.reload_interval) ): # pragma: nocover pass self.monitor.clear_changes() def _start_monitor(self): self.monitor = FileMonitorProxy(self.monitor_factory, self.verbose) self.monitor.start() def _stop_monitor(self): if self.monitor: self.monitor.stop() self.monitor = None def _capture_signals(self): # SIGHUP is not supported on windows if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, self._signal_sighup) def _signal_sighup(self, signum, frame): self.out('Received SIGHUP, triggering a reload.') self.monitor.set_changed() def _restore_signals(self): if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, signal.SIG_DFL) def start_reloader( worker_path, reload_interval=1, verbose=1, monitor_factory=None, worker_args=None, worker_kwargs=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog `_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. """ if is_active(): return get_reloader() if monitor_factory is None: if is_watchdog_supported(): from .watchdog import WatchdogFileMonitor def monitor_factory(callback): return WatchdogFileMonitor(callback) if verbose > 1: print('File monitor backend: watchdog') else: from .polling import PollingFileMonitor def monitor_factory(callback): return PollingFileMonitor(callback, reload_interval) if verbose > 1: print('File monitor backend: polling') reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, verbose=verbose, monitor_factory=monitor_factory, ) return reloader.run() hupper-1.0/src/hupper/watchdog.py0000644000076500000240000000275413105222712017651 0ustar michaelstaff00000000000000# check ``hupper.compat.is_watchdog_supported`` before using this module from __future__ import absolute_import import os.path import threading from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from .interfaces import IFileMonitor class WatchdogFileMonitor(FileSystemEventHandler, Observer, IFileMonitor): """ An :class:`hupper.interfaces.IFileMonitor` that uses ``watchdog`` to watch for file changes uses inotify. ``callback`` is a callable that accepts a path to a changed file. """ def __init__(self, callback): super(WatchdogFileMonitor, self).__init__() self.callback = callback self.paths = set() self.dirpaths = set() self.lock = threading.Lock() def add_path(self, path): with self.lock: dirpath = os.path.dirname(path) if dirpath not in self.dirpaths: try: self.schedule(self, dirpath) except (OSError, IOError): # pragma: no cover # ideally we would handle this better but if the # directory is missing watchdog raises an error pass else: self.dirpaths.add(dirpath) if path not in self.paths: self.paths.add(path) def on_any_event(self, event): with self.lock: path = event.src_path if path in self.paths: self.callback(path) hupper-1.0/src/hupper/winapi.py0000644000076500000240000001073513104736376017355 0ustar michaelstaff00000000000000import ctypes from ctypes import wintypes kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) if ctypes.sizeof(ctypes.c_void_p) == 8: ULONG_PTR = ctypes.c_int64 else: ULONG_PTR = ctypes.c_ulong BOOL = wintypes.BOOL DWORD = wintypes.DWORD HANDLE = wintypes.HANDLE LARGE_INTEGER = wintypes.LARGE_INTEGER SIZE_T = ULONG_PTR ULONGLONG = ctypes.c_uint64 JobObjectAssociateCompletionPortInformation = 7 JobObjectBasicLimitInformation = 2 JobObjectBasicUIRestrictions = 4 JobObjectEndOfJobTimeInformation = 6 JobObjectExtendedLimitInformation = 9 JobObjectSecurityLimitInformation = 5 JobObjectGroupInformation = 11 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 DELETE = 0x00010000 READ_CONTROL = 0x00020000 SYNCHRONIZE = 0x00100000 WRITE_DAC = 0x00040000 WRITE_OWNER = 0x00080000 STANDARD_RIGHTS_REQUIRED = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER PROCESS_CREATE_PROCESS = 0x0080 PROCESS_CREATE_THREAD = 0x0002 PROCESS_DUP_HANDLE = 0x0040 PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 PROCESS_SET_INFORMATION = 0x0200 PROCESS_SET_QUOTA = 0x0100 PROCESS_SUSPEND_RESUME = 0x0800 PROCESS_TERMINATE = 0x0001 PROCESS_VM_OPERATION = 0x0008 PROCESS_VM_READ = 0x0010 PROCESS_VM_WRITE = 0x0020 PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF DUPLICATE_SAME_ACCESS = 0x0002 HANDLE_FLAG_INHERIT = 0x0001 HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x0002 class IO_COUNTERS(ctypes.Structure): _fields_ = [ ('ReadOperationCount', ULONGLONG), ('WriteOperationCount', ULONGLONG), ('OtherOperationCount', ULONGLONG), ('ReadTransferCount', ULONGLONG), ('WriteTransferCount', ULONGLONG), ('OtherTransferCount', ULONGLONG), ] class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ('PerProcessUserTimeLimit', LARGE_INTEGER), ('PerJobUserTimeLimit', LARGE_INTEGER), ('LimitFlags', DWORD), ('MinimumWorkingSetSize', SIZE_T), ('MaximumWorkingSetSize', SIZE_T), ('ActiveProcessLimit', DWORD), ('Affinity', ULONG_PTR), ('PriorityClass', DWORD), ('SchedulingClass', DWORD), ] class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION), ('IoInfo', IO_COUNTERS), ('ProcessMemoryLimit', SIZE_T), ('JobMemoryLimit', SIZE_T), ('PeakProcessMemoryUsed', SIZE_T), ('PeakJobMemoryUsed', SIZE_T), ] class Handle(HANDLE): closed = False def Close(self): if not self.closed: self.closed = True CloseHandle(self) def Detach(self): if not self.closed: self.closed = True return self.value raise ValueError("already closed") def __repr__(self): return "%s(%d)" % (self.__class__.__name__, self.value) __del__ = Close __str__ = __repr__ def CloseHandle(h): kernel32.CloseHandle(h) def CheckError(result, msg): if not result: raise ctypes.WinError(ctypes.get_last_error(), msg) def DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, desiredAccess, inheritHandle, options ): targetHandle = wintypes.HANDLE() ret = kernel32.DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, ctypes.byref(targetHandle), desiredAccess, inheritHandle, options, ) CheckError(ret, 'failed to duplicate handle') return Handle(targetHandle.value) def GetCurrentProcess(): hp = kernel32.GetCurrentProcess() return Handle(hp) def OpenProcess(desiredAccess, inherit, pid): hp = kernel32.OpenProcess(desiredAccess, inherit, pid) CheckError(hp, 'failed to open process') return Handle(hp) def CreateJobObject(jobAttributes, name): hp = kernel32.CreateJobObjectA(jobAttributes, name) CheckError(hp, 'failed to create job object') return Handle(hp) def SetInformationJobObject(hJob, infoType, jobObjectInfo): ret = kernel32.SetInformationJobObject( hJob, infoType, ctypes.byref(jobObjectInfo), ctypes.sizeof(jobObjectInfo), ) CheckError(ret, 'failed to set information job object') def AssignProcessToJobObject(hJob, hProcess): ret = kernel32.AssignProcessToJobObject(hJob, hProcess) CheckError(ret, 'failed to assign process to job object') def SetHandleInformation(h, dwMask, dwFlags): ret = kernel32.SetHandleInformation(h, dwMask, dwFlags) CheckError(ret, 'failed to set handle information')hupper-1.0/src/hupper/worker.py0000644000076500000240000001534313104736376017377 0ustar michaelstaff00000000000000import os import signal import sys import threading import time import traceback from .compat import get_pyc_path from .compat import get_py_path from .compat import interrupt_main from .interfaces import IReloaderProxy from . import ipc class WatchSysModules(threading.Thread): """ Poll ``sys.modules`` for imported modules.""" poll_interval = 1 def __init__(self, callback): super(WatchSysModules, self).__init__() self.paths = set() self.callback = callback self.lock = threading.Lock() self.stopped = False def run(self): while not self.stopped: self.update_paths() time.sleep(self.poll_interval) def stop(self): self.stopped = True def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.callback(new_paths) def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.callback(new_paths) def expand_source_paths(paths): """ Convert pyc files into their source equivalents.""" for src_path in paths: yield src_path # track pyc files for py files if src_path.endswith('.py'): pyc_path = get_pyc_path(src_path) if pyc_path: yield pyc_path # track py files for pyc files elif src_path.endswith('.pyc'): py_path = get_py_path(src_path) if py_path: yield py_path def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: nocover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename class WatchForParentShutdown(threading.Thread): """ Watch the pipe to ensure the parent is still alive.""" def __init__(self, pipe): super(WatchForParentShutdown, self).__init__() self.pipe = pipe def run(self): try: # wait until the pipe breaks while self.pipe.recv(): # pragma: nocover pass except EOFError: pass interrupt_main() class Worker(object): """ A helper object for managing a worker process lifecycle. """ def __init__(self, spec, args=None, kwargs=None): super(Worker, self).__init__() self.worker_spec = spec self.worker_args = args self.worker_kwargs = kwargs self.pipe, self._child_pipe = ipc.Pipe() self.terminated = False self.pid = None self.process = None self.exitcode = None self.stdin_termios = None def start(self): self.stdin_termios = ipc.snapshot_termios(sys.stdin.fileno()) kw = dict( spec=self.worker_spec, spec_args=self.worker_args, spec_kwargs=self.worker_kwargs, pipe=self._child_pipe, ) self.process = ipc.spawn( 'hupper.worker.worker_main', kwargs=kw, pass_fds=[self._child_pipe.r_fd, self._child_pipe.w_fd], ) self.pid = self.process.pid # activate the pipe after forking self.pipe.activate() # kill the child side of the pipe after forking as the child is now # responsible for it self._child_pipe.close() def is_alive(self): if self.process: return self.process.poll() is None return False def terminate(self): self.terminated = True self.process.terminate() def join(self): self.process.wait() self.exitcode = self.process.returncode if self.stdin_termios: ipc.restore_termios(sys.stdin.fileno(), self.stdin_termios) if self.pipe: try: self.pipe.close() except: # pragma: nocover pass finally: self.pipe = None # set when the current process is being monitored _reloader_proxy = None def get_reloader(): """ Get a reference to the current :class:`hupper.interfaces.IReloaderProxy`. Raises a ``RuntimeError`` if the current process is not actively being monitored by a parent process. """ if _reloader_proxy is None: raise RuntimeError('process is not controlled by hupper') return _reloader_proxy def is_active(): """ Return ``True`` if the current process being monitored by a parent process. """ return _reloader_proxy is not None class ReloaderProxy(IReloaderProxy): def __init__(self, pipe): self.pipe = pipe def watch_files(self, files): self.pipe.send(('watch', files)) def trigger_reload(self): self.pipe.send(('reload',)) def worker_main(spec, pipe, spec_args=None, spec_kwargs=None): if spec_args is None: spec_args = [] if spec_kwargs is None: spec_kwargs = {} # activate the pipe after forking pipe.activate() # SIGHUP is not supported on windows if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, signal.SIG_IGN) # disable pyc files for project code because it can cause timestamp # issues in which files are reloaded twice sys.dont_write_bytecode = True global _reloader_proxy _reloader_proxy = ReloaderProxy(pipe) parent_watcher = WatchForParentShutdown(pipe) parent_watcher.daemon = True parent_watcher.start() poller = WatchSysModules(_reloader_proxy.watch_files) poller.daemon = True poller.start() # import the worker path before polling sys.modules func = ipc.resolve_spec(spec) # start the worker try: func(*spec_args, **spec_kwargs) except: try: # attempt to send imported paths to the master prior to crashing poller.update_paths() poller.search_traceback(sys.exc_info()[2]) poller.stop() poller.join() except: # pragma: no cover pass raise hupper-1.0/src/hupper.egg-info/0000755000076500000240000000000013107411503017161 5ustar michaelstaff00000000000000hupper-1.0/src/hupper.egg-info/dependency_links.txt0000644000076500000240000000000113107411503023227 0ustar michaelstaff00000000000000 hupper-1.0/src/hupper.egg-info/entry_points.txt0000644000076500000240000000005413107411503022456 0ustar michaelstaff00000000000000[console_scripts] hupper = hupper.cli:main hupper-1.0/src/hupper.egg-info/not-zip-safe0000644000076500000240000000000113104230575021414 0ustar michaelstaff00000000000000 hupper-1.0/src/hupper.egg-info/PKG-INFO0000644000076500000240000002042113107411503020255 0ustar michaelstaff00000000000000Metadata-Version: 1.2 Name: hupper Version: 1.0 Summary: Integrated process monitor for developing and reloading daemons. Home-page: https://github.com/Pylons/hupper Author: Michael Merickel Author-email: pylons-discuss@googlegroups.com License: MIT Description: ====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain']) yield [b'hello'] def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. 1.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. Keywords: server daemon autoreload reloader hup file watch process Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* hupper-1.0/src/hupper.egg-info/requires.txt0000644000076500000240000000013013107411503021553 0ustar michaelstaff00000000000000 [docs] watchdog Sphinx pylons-sphinx-themes [testing] watchdog pytest pytest-cov mock hupper-1.0/src/hupper.egg-info/SOURCES.txt0000644000076500000240000000157513107411503021055 0ustar michaelstaff00000000000000.coveragerc .travis.yml CHANGES.rst CONTRIBUTING.rst LICENSE.txt MANIFEST.in README.rst appveyor.yml rtd.txt setup.cfg setup.py tox.ini docs/Makefile docs/api.rst docs/changes.rst docs/conf.py docs/contributing.rst docs/index.rst docs/make.bat docs/_static/.keep src/hupper/__init__.py src/hupper/cli.py src/hupper/compat.py src/hupper/interfaces.py src/hupper/ipc.py src/hupper/polling.py src/hupper/reloader.py src/hupper/watchdog.py src/hupper/winapi.py src/hupper/worker.py src/hupper.egg-info/PKG-INFO src/hupper.egg-info/SOURCES.txt src/hupper.egg-info/dependency_links.txt src/hupper.egg-info/entry_points.txt src/hupper.egg-info/not-zip-safe src/hupper.egg-info/requires.txt src/hupper.egg-info/top_level.txt tests/__init__.py tests/conftest.py tests/test_it.py tests/test_reloader.py tests/util.py tests/myapp/__init__.py tests/myapp/__main__.py tests/myapp/cli.py tests/myapp/foo.inihupper-1.0/src/hupper.egg-info/top_level.txt0000644000076500000240000000000713107411503021710 0ustar michaelstaff00000000000000hupper hupper-1.0/tests/0000755000076500000240000000000013107411503014537 5ustar michaelstaff00000000000000hupper-1.0/tests/__init__.py0000644000076500000240000000000013007726651016652 0ustar michaelstaff00000000000000hupper-1.0/tests/conftest.py0000644000076500000240000000165313105250315016743 0ustar michaelstaff00000000000000from __future__ import print_function import pytest import sys from . import util def err(msg): # pragma: no cover print(msg, file=sys.stderr) @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # execute all other hooks to obtain the report object outcome = yield rep = outcome.get_result() # set an report attribute for each phase of a call, which can # be "setup", "call", "teardown" setattr(item, "rep_" + rep.when, rep) @pytest.fixture def testapp(request): app = util.TestApp() try: yield app finally: app.stop() if ( request.node.rep_call.failed and app.exitcode is not None ): # pragma: no cover err('-- test app failed --\nname=%s\nargs=%s\ncode=%s' % ( app.name, app.args, app.exitcode)) err('-- stdout --\n%s' % app.stdout) err('-- stderr --\n%s' % app.stderr) hupper-1.0/tests/myapp/0000755000076500000240000000000013107411503015665 5ustar michaelstaff00000000000000hupper-1.0/tests/myapp/__init__.py0000644000076500000240000000037013105224304017775 0ustar michaelstaff00000000000000import pytest_cov.embed import signal import sys def cleanup(*args, **kwargs): # pragma: no cover # see https://github.com/pytest-dev/pytest-cov/issues/139 pytest_cov.embed.cleanup() sys.exit(1) signal.signal(signal.SIGTERM, cleanup) hupper-1.0/tests/myapp/__main__.py0000644000076500000240000000010413014167372017763 0ustar michaelstaff00000000000000import sys from .cli import main sys.exit(main(sys.argv[1:]) or 0) hupper-1.0/tests/myapp/cli.py0000644000076500000240000000332113106732431017012 0ustar michaelstaff00000000000000import argparse import hupper import os import sys import time here = os.path.dirname(__file__) def parse_options(args): parser = argparse.ArgumentParser() parser.add_argument('--reload', action='store_true') parser.add_argument('--callback-file') parser.add_argument('--watch-file', action='append', dest='watch_files', default=[]) parser.add_argument('--watchdog', action='store_true') parser.add_argument('--poll', action='store_true') parser.add_argument('--poll-interval', type=int) parser.add_argument('--reload-interval', type=int) return parser.parse_args(args) def main(args=None): if args is None: args = sys.argv[1:] opts = parse_options(args) if opts.reload: kw = {} if opts.poll: from hupper.polling import PollingFileMonitor pkw = {} if opts.poll_interval: pkw['poll_interval'] = opts.poll_interval kw['monitor_factory'] = lambda cb: PollingFileMonitor(cb, **pkw) if opts.watchdog: from hupper.watchdog import WatchdogFileMonitor kw['monitor_factory'] = WatchdogFileMonitor if opts.reload_interval: kw['reload_interval'] = opts.reload_interval hupper.start_reloader(__name__ + '.main', **kw) if hupper.is_active(): hupper.get_reloader().watch_files([os.path.join(here, 'foo.ini')]) hupper.get_reloader().watch_files(opts.watch_files) if opts.callback_file: with open(opts.callback_file, 'ab') as fp: fp.write('{:d}\n'.format(int(time.time())).encode('utf8')) try: while True: time.sleep(1) except KeyboardInterrupt: pass hupper-1.0/tests/myapp/foo.ini0000644000076500000240000000000013106732422017144 0ustar michaelstaff00000000000000hupper-1.0/tests/test_it.py0000644000076500000240000000134013104767143016575 0ustar michaelstaff00000000000000import os.path import time from . import util here = os.path.abspath(os.path.dirname(__file__)) def test_myapp_reloads_when_touching_ini(testapp): testapp.start('myapp', ['--reload']) testapp.wait_for_response() time.sleep(2) util.touch(os.path.join(here, 'myapp/foo.ini')) testapp.wait_for_response() testapp.stop() assert len(testapp.response) == 2 assert testapp.stdout != '' def test_myapp_reloads_when_touching_pyfile(testapp): testapp.start('myapp', ['--reload']) testapp.wait_for_response() time.sleep(2) util.touch(os.path.join(here, 'myapp/cli.py')) testapp.wait_for_response() testapp.stop() assert len(testapp.response) == 2 assert testapp.stdout != '' hupper-1.0/tests/test_reloader.py0000644000076500000240000000421513014745164017761 0ustar michaelstaff00000000000000import os here = os.path.abspath(os.path.dirname(__file__)) def make_proxy(*args, **kwargs): from hupper.reloader import FileMonitorProxy return FileMonitorProxy(*args, **kwargs) def test_proxy_proxies(): class DummyMonitor(object): started = stopped = joined = False def __call__(self, cb): self.cb = cb return self def start(self): self.started = True def stop(self): self.stopped = True def join(self): self.joined = True monitor = DummyMonitor() proxy = make_proxy(monitor) assert monitor.cb assert not monitor.started and not monitor.stopped and not monitor.joined proxy.start() assert monitor.started and not monitor.stopped and not monitor.joined proxy.stop() assert monitor.stopped and monitor.joined def test_proxy_expands_paths(tmpdir): class DummyMonitor(object): def __call__(self, cb): self.cb = cb self.paths = [] return self def add_path(self, path): self.paths.append(path) monitor = DummyMonitor() proxy = make_proxy(monitor) proxy.add_path('foo') assert monitor.paths == ['foo'] tmpdir.join('foo.txt').ensure() tmpdir.join('bar.txt').ensure() rootdir = tmpdir.strpath monitor.paths = [] proxy.add_path(os.path.join(rootdir, '*.txt')) assert sorted(monitor.paths) == [ os.path.join(rootdir, 'bar.txt'), os.path.join(rootdir, 'foo.txt'), ] def test_proxy_tracks_changes(capsys): class DummyMonitor(object): def __call__(self, cb): self.cb = cb return self monitor = DummyMonitor() proxy = make_proxy(monitor) assert not proxy.is_changed() monitor.cb('foo.txt') assert proxy.is_changed() out, err = capsys.readouterr() assert out == 'foo.txt changed; reloading ...\n' monitor.cb('foo.txt') out, err = capsys.readouterr() assert out == '' proxy.clear_changes() assert not proxy.is_changed() monitor.cb('foo.txt') out, err = capsys.readouterr() assert out == 'foo.txt changed; reloading ...\n' hupper-1.0/tests/util.py0000644000076500000240000000527313103247661016105 0ustar michaelstaff00000000000000import os import subprocess import sys import tempfile import threading import time here = os.path.abspath(os.path.dirname(__file__)) class TestApp(threading.Thread): name = None args = None stdin = None daemon = True def __init__(self): super(TestApp, self).__init__() self.exitcode = None self.process = None self.tmpfile = None self.tmpsize = 0 self.response = None self.stdout, self.stderr = b'', b'' def start(self, name, args): self.name = name self.args = args or [] fd, self.tmpfile = tempfile.mkstemp() os.close(fd) touch(self.tmpfile) self.tmpsize = os.path.getsize(self.tmpfile) self.response = readfile(self.tmpfile) super(TestApp, self).start() def run(self): cmd = [sys.executable, '-m', 'tests.' + self.name] if self.tmpfile: cmd += ['--callback-file', self.tmpfile] cmd += self.args env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' self.process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, universal_newlines=True, ) try: self.stdout, self.stderr = self.process.communicate(self.stdin) finally: self.exitcode = self.process.wait() def is_alive(self): return self.process is not None and self.exitcode is None def stop(self): if self.is_alive(): self.process.terminate() self.join() if self.tmpfile: os.unlink(self.tmpfile) self.tmpfile = None def wait_for_response(self, timeout=5, interval=0.1): self.tmpsize = wait_for_change( self.tmpfile, last_size=self.tmpsize, timeout=timeout, interval=interval, ) self.response = readfile(self.tmpfile) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def readfile(path): with open(path, 'rb') as fp: return fp.readlines() def wait_for_change(path, last_size=0, timeout=5, interval=0.1): start = time.time() size = os.path.getsize(path) while size == last_size: duration = time.time() - start sleepfor = interval if timeout is not None: # pragma: no cover if duration >= timeout: raise RuntimeError( 'timeout waiting for change to file=%s' % (path,)) sleepfor = min(timeout - duration, sleepfor) time.sleep(sleepfor) size = os.path.getsize(path) return size hupper-1.0/tox.ini0000644000076500000240000000142613105251451014715 0ustar michaelstaff00000000000000[tox] envlist = py27,py34,py35,py36,pypy, pep8,docs,coverage [testenv] basepython = py27: python2.7 py34: python3.4 py35: python3.5 py36: python3.6 pypy: pypy py2: python2.7 py3: python3.6 pypy3: pypy3 commands = pip install hupper[testing] py.test --cov --cov-report= {posargs:} setenv = COVERAGE_FILE=.coverage.{envname} [testenv:coverage] basepython = python3.6 commands = coverage combine coverage report deps = coverage setenv = COVERAGE_FILE=.coverage [testenv:docs] basepython = python3.6 whitelist_externals = make commands = pip install hupper[docs] make -C docs html BUILDDIR={envdir} SPHINXOPTS="-W -E" [testenv:pep8] basepython = python3.6 commands = flake8 src/hupper/ deps = flake8