├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py ├── contributing.rst ├── index.rst ├── make.bat ├── shell_api.rst ├── testing.rst └── tutorial.rst ├── setup.cfg ├── setup.py ├── shell.py └── tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | __pycache__ 3 | *.pyc 4 | build 5 | dist 6 | shell.egg-info 7 | docs/_build 8 | env 9 | env3 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, Daniel Lindsley. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | 3. Neither the name of shell nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without 16 | specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 25 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | shell 3 | ===== 4 | 5 | """A better way to run shell commands in Python.""" 6 | 7 | Built because every time I go to use `subprocess`_, I spend more time in the 8 | docs & futzing around than actually implementing what I'm trying to get done. 9 | 10 | .. _`subprocess`: http://docs.python.org/2.7/library/subprocess.html 11 | 12 | Full docs are at https://shell.readthedocs.org/en/latest/. 13 | 14 | 15 | Requirements 16 | ============ 17 | 18 | * Python 2.6+ or Python 3.3+ 19 | 20 | 21 | Usage 22 | ===== 23 | 24 | If you just need to quickly run a command, you can use the ``shell`` shortcut 25 | function:: 26 | 27 | >>> from shell import shell 28 | >>> ls = shell('ls') 29 | >>> for file in ls.output(): 30 | ... print file 31 | 'another.txt' 32 | 33 | If you need to extend the behavior, you can also use the ``Shell`` object:: 34 | 35 | >>> from shell import Shell 36 | >>> sh = Shell(has_input=True) 37 | >>> cat = sh.run('cat -u') 38 | >>> cat.write('Hello, world!') 39 | >>> cat.output() 40 | ['Hello, world!'] 41 | 42 | You can even chain calls if you'd like:: 43 | 44 | >>> from shell import shell 45 | >>> shell('cat -u', has_input=True).write('Hello, world!').output() 46 | ['Hello, world!'] 47 | 48 | 49 | Installation 50 | ============ 51 | 52 | Using ``pip``, simply run:: 53 | 54 | pip install shell 55 | 56 | 57 | License 58 | ======= 59 | 60 | New BSD 61 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/shell.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/shell.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/shell" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/shell" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # shell documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Jun 2 12:36:25 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc',] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'shell' 44 | copyright = u'2013, Daniel Lindsley' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '1.0.1' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '1.0.1' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'shelldoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'shell.tex', u'shell Documentation', 182 | u'Daniel Lindsley', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # If true, show page references after internal links. 194 | #latex_show_pagerefs = False 195 | 196 | # If true, show URL addresses after external links. 197 | #latex_show_urls = False 198 | 199 | # Additional stuff for the LaTeX preamble. 200 | #latex_preamble = '' 201 | 202 | # Documents to append as an appendix to all manuals. 203 | #latex_appendices = [] 204 | 205 | # If false, no module index is generated. 206 | #latex_domain_indices = True 207 | 208 | 209 | # -- Options for manual page output -------------------------------------------- 210 | 211 | # One entry per manual page. List of tuples 212 | # (source start file, name, description, authors, manual section). 213 | man_pages = [ 214 | ('index', 'shell', u'shell Documentation', 215 | [u'Daniel Lindsley'], 1) 216 | ] 217 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | To contribute to ``shell``, it must meet the following criteria: 6 | 7 | * Has a failing test case (see ``tests.py`` & :ref:`testing`) without the fix 8 | * Has a fix that matches existing style 9 | * Has docstrings 10 | * Adds to the documentation if the change is user-facing 11 | * Is BSD-compatibly licensed 12 | 13 | Please create fork on Github, clone your fork, create a new branch, make your 14 | changes on that branch, push it back to Github & open a pull request. 15 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. shell documentation master file, created by 2 | sphinx-quickstart on Sun Jun 2 12:36:25 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | shell's Documentation 7 | ===================== 8 | 9 | """A better way to run shell commands in Python.""" 10 | 11 | Built because every time I go to use `subprocess`_, I spend more time in the 12 | docs & futzing around than actually implementing what I'm trying to get done. 13 | 14 | .. _`subprocess`: http://docs.python.org/2.7/library/subprocess.html 15 | 16 | 17 | Philosophy 18 | ---------- 19 | 20 | * Makes running commands more natural 21 | * Assumes you care about the output/errors by default 22 | * Covers the 80% case of running commands 23 | * A nicer API 24 | * Works on Linux/OS X (untested on Windows but might work?) 25 | 26 | 27 | Contents: 28 | 29 | .. toctree:: 30 | :maxdepth: 2 31 | 32 | tutorial 33 | shell_api 34 | testing 35 | contributing 36 | 37 | 38 | Indices and tables 39 | ================== 40 | 41 | * :ref:`genindex` 42 | * :ref:`modindex` 43 | * :ref:`search` 44 | 45 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. changes to make an overview over all changed/added/deprecated items 32 | echo. linkcheck to check all external links for integrity 33 | echo. doctest to run all doctests embedded in the documentation if enabled 34 | goto end 35 | ) 36 | 37 | if "%1" == "clean" ( 38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 39 | del /q /s %BUILDDIR%\* 40 | goto end 41 | ) 42 | 43 | if "%1" == "html" ( 44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 45 | if errorlevel 1 exit /b 1 46 | echo. 47 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 48 | goto end 49 | ) 50 | 51 | if "%1" == "dirhtml" ( 52 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 53 | if errorlevel 1 exit /b 1 54 | echo. 55 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 56 | goto end 57 | ) 58 | 59 | if "%1" == "singlehtml" ( 60 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 61 | if errorlevel 1 exit /b 1 62 | echo. 63 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 64 | goto end 65 | ) 66 | 67 | if "%1" == "pickle" ( 68 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 69 | if errorlevel 1 exit /b 1 70 | echo. 71 | echo.Build finished; now you can process the pickle files. 72 | goto end 73 | ) 74 | 75 | if "%1" == "json" ( 76 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished; now you can process the JSON files. 80 | goto end 81 | ) 82 | 83 | if "%1" == "htmlhelp" ( 84 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished; now you can run HTML Help Workshop with the ^ 88 | .hhp project file in %BUILDDIR%/htmlhelp. 89 | goto end 90 | ) 91 | 92 | if "%1" == "qthelp" ( 93 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 94 | if errorlevel 1 exit /b 1 95 | echo. 96 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 97 | .qhcp project file in %BUILDDIR%/qthelp, like this: 98 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\shell.qhcp 99 | echo.To view the help file: 100 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\shell.ghc 101 | goto end 102 | ) 103 | 104 | if "%1" == "devhelp" ( 105 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 106 | if errorlevel 1 exit /b 1 107 | echo. 108 | echo.Build finished. 109 | goto end 110 | ) 111 | 112 | if "%1" == "epub" ( 113 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 117 | goto end 118 | ) 119 | 120 | if "%1" == "latex" ( 121 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 122 | if errorlevel 1 exit /b 1 123 | echo. 124 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 125 | goto end 126 | ) 127 | 128 | if "%1" == "text" ( 129 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 130 | if errorlevel 1 exit /b 1 131 | echo. 132 | echo.Build finished. The text files are in %BUILDDIR%/text. 133 | goto end 134 | ) 135 | 136 | if "%1" == "man" ( 137 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 141 | goto end 142 | ) 143 | 144 | if "%1" == "changes" ( 145 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.The overview file is in %BUILDDIR%/changes. 149 | goto end 150 | ) 151 | 152 | if "%1" == "linkcheck" ( 153 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Link check complete; look for any errors in the above output ^ 157 | or in %BUILDDIR%/linkcheck/output.txt. 158 | goto end 159 | ) 160 | 161 | if "%1" == "doctest" ( 162 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 163 | if errorlevel 1 exit /b 1 164 | echo. 165 | echo.Testing of doctests in the sources finished, look at the ^ 166 | results in %BUILDDIR%/doctest/output.txt. 167 | goto end 168 | ) 169 | 170 | :end 171 | -------------------------------------------------------------------------------- /docs/shell_api.rst: -------------------------------------------------------------------------------- 1 | .. ref-shell_api 2 | 3 | ========= 4 | Shell API 5 | ========= 6 | 7 | shell 8 | ----- 9 | 10 | .. automodule:: shell 11 | :members: 12 | :undoc-members: 13 | -------------------------------------------------------------------------------- /docs/testing.rst: -------------------------------------------------------------------------------- 1 | ============= 2 | Testing shell 3 | ============= 4 | 5 | ``shell`` maintains 100% passing tests at all times. That said, there are 6 | undoubtedly bugs or odd configurations it doesn't cover. 7 | 8 | 9 | Setup 10 | ===== 11 | 12 | Getting setup to run tests (Python 2) looks like:: 13 | 14 | $ git clone https://github.com/toastdriven/shell 15 | $ cd shell 16 | $ virtualenv env 17 | $ . env/bin/activate 18 | $ pip install mock==1.0.1 19 | $ pip install nose==1.3.0 20 | 21 | Once that's setup, setting up for Python 3 looks like:: 22 | 23 | $ virtualenv -p python3 env3 24 | $ . env3/bin/activate 25 | $ pip install mock==1.0.1 26 | $ pip install nose==1.3.0 27 | 28 | 29 | Running the tests 30 | ================= 31 | 32 | To run the tests, run the following:: 33 | 34 | $ nosetests -s tests.py 35 | -------------------------------------------------------------------------------- /docs/tutorial.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | shell Tutorial 3 | ============== 4 | 5 | If you've ever tried to run a shell command in Python, you're likely unhappy 6 | about it. The ``subprocess`` module, while a huge & consistent step forward 7 | over the previous ways Python shelled out, has a rather painful interface. 8 | If you're like me, you spent more time in the docs than you did writing working 9 | code. 10 | 11 | ``shell`` tries to fix this, by glossing over the warts in the ``subprocess`` 12 | API & making running commands *easy*. 13 | 14 | 15 | Installation 16 | ============ 17 | 18 | If you're developing in Python, you ought to be using `pip`_. Installing (from 19 | your terminal) looks like:: 20 | 21 | $ pip install shell 22 | 23 | .. _`pip`: http://www.pip-installer.org/en/latest/ 24 | 25 | 26 | Quickstart 27 | ========== 28 | 29 | For the impatient:: 30 | 31 | >>> from shell import shell 32 | >>> ls = shell('ls') 33 | >>> for file in ls.output(): 34 | ... print file 35 | 'another.txt' 36 | 37 | # Or if you need more control, the same code can be stated as... 38 | >>> from shell import Shell 39 | >>> sh = Shell() 40 | >>> sh.run('ls') 41 | >>> for file in sh.output(): 42 | ... print file 43 | 'another.txt' 44 | 45 | 46 | Getting Started 47 | =============== 48 | 49 | Importing 50 | --------- 51 | 52 | The first thing you'll need to do is import ``shell``. You can either use 53 | the easy functional version:: 54 | 55 | >>> from shell import shell 56 | 57 | Or the class-based & extensible version:: 58 | 59 | >>> from shell import Shell 60 | 61 | 62 | Your First Command 63 | ------------------ 64 | 65 | Running a basic command is simple. Simply hand the command you'd use at the 66 | terminal off to ``shell``:: 67 | 68 | >>> from shell import shell 69 | >>> shell('touch hello_world.txt') 70 | 71 | # The class-based variant. 72 | >>> from shell import Shell 73 | >>> sh = Shell() 74 | >>> sh.run('touch hello_world.txt') 75 | 76 | You should now have a ``hello_world.txt`` file created in your current 77 | directory. 78 | 79 | 80 | Reading Output 81 | -------------- 82 | 83 | By default, ``shell`` captures output/errors from the command being run. You can 84 | read the output & errors like so:: 85 | 86 | >>> from shell import shell 87 | >>> sh = shell('ls /tmp') 88 | # Your output from these calls will vary... 89 | >>> sh.output() 90 | [ 91 | 'hello.txt', 92 | 'world.py', 93 | ] 94 | >>> sh.errors() 95 | [] 96 | 97 | # The class-based variant. 98 | >>> from shell import Shell 99 | >>> sh = Shell() 100 | >>> sh.run('ls /tmp') 101 | >>> sh.output() 102 | [ 103 | 'hello.txt', 104 | 'world.py', 105 | ] 106 | >>> sh.errors() 107 | [] 108 | 109 | You can also look at what the process ID was & the return code.:: 110 | 111 | >>> sh.pid 112 | 15172 113 | >>> sh.code 114 | 0 115 | 116 | Getting a ``0`` from ``sh.code`` means a process finished sucessfully. Higher 117 | integer return values generally mean there was an error. 118 | 119 | 120 | Interactive 121 | ----------- 122 | 123 | If the command is interactive, you can send it input as well.:: 124 | 125 | >>> from shell import shell 126 | >>> sh = shell('cat -u', has_input=True) 127 | >>> sh.write('Hello, world!') 128 | >>> sh.output() 129 | [ 130 | 'Hello, world!' 131 | ] 132 | 133 | # The class-based variant. 134 | >>> from shell import Shell 135 | >>> sh = Shell(has_input=True) 136 | >>> sh.run('cat -u') 137 | >>> sh.write('Hello, world!') 138 | >>> sh.output() 139 | [ 140 | 'Hello, world!' 141 | ] 142 | 143 | .. warning:: 144 | 145 | You get one shot at sending input, after which the command will finish. 146 | Using ``shell`` for advanced, multi-prompt shell commands is likely is not 147 | a good option. 148 | 149 | 150 | Failing Fast 151 | ------------ 152 | 153 | You can have non-zero exit codes propagate as exceptions:: 154 | 155 | >>> from shell import shell 156 | >>> shell('ls /not/a/real/place', die=True) 157 | Traceback (most recent call last): 158 | ... 159 | shell.CommandError: Command exited with code 1 160 | >>> import sys 161 | >>> from shell import CommandError 162 | >>> try: 163 | >>> shell('ls /also/definitely/fake', die=True) 164 | >>> except CommandError, e: 165 | >>> print e.stderr 166 | >>> sys.exit(e.code) 167 | ls: /also/definitely/fake: No such file or directory 168 | $ echo $? 169 | 1 170 | 171 | 172 | Chaining 173 | -------- 174 | 175 | You can also chain calls together, if that suits you.:: 176 | 177 | >>> from shell import shell 178 | >>> shell('cat -u', has_input=True).write('Hello, world!').output() 179 | [ 180 | 'Hello, world!' 181 | ] 182 | 183 | # The class-based variant. 184 | >>> from shell import Shell 185 | >>> Shell(has_input=True).run('cat -u').write('Hello, world!').output() 186 | [ 187 | 'Hello, world!' 188 | ] 189 | 190 | 191 | Ignoring Large Output 192 | --------------------- 193 | 194 | By default, ``shell`` captures all output/errors. If you have a command that 195 | generates a large volume of output that you don't care about, you can ignore 196 | it like so.:: 197 | 198 | >>> from shell import shell 199 | >>> sh = shell('run_intensive_command -v', record_output=False, record_errors=False) 200 | >>> sh.code 201 | 0 202 | 203 | # The class-based variant. 204 | >>> from shell import Shell 205 | >>> sh = Shell(record_output=False, record_errors=False) 206 | >>> sh.run('run_intensive_command -v') 207 | >>> sh.code 208 | 0 209 | 210 | 211 | What Now? 212 | ========= 213 | 214 | If you need more advanced functionality, subclassing the ``Shell`` class is the 215 | best place to start. 216 | 217 | You can find more details about it in the :doc:`shell_api`. 218 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | 7 | setup( 8 | name="shell", 9 | version="1.0.1", 10 | description="A better way to run shell commands in Python.", 11 | author='Daniel Lindsley', 12 | author_email='daniel@toastdriven.com', 13 | long_description=open('README.rst', 'r').read(), 14 | py_modules=[ 15 | 'shell' 16 | ], 17 | classifiers=[ 18 | 'Development Status :: 5 - Production/Stable', 19 | 'Intended Audience :: Developers', 20 | 'License :: OSI Approved :: BSD License', 21 | 'Operating System :: OS Independent', 22 | 'Programming Language :: Python', 23 | 'Topic :: System :: Shells', 24 | 'Programming Language :: Python :: 2', 25 | 'Programming Language :: Python :: 3', 26 | ], 27 | url='http://github.com/toastdriven/shell', 28 | license='BSD' 29 | ) 30 | -------------------------------------------------------------------------------- /shell.py: -------------------------------------------------------------------------------- 1 | """ 2 | shell 3 | ===== 4 | 5 | A better way to run shell commands in Python. 6 | 7 | If you just need to quickly run a command, you can use the ``shell`` shortcut 8 | function:: 9 | 10 | >>> from shell import shell 11 | >>> ls = shell('ls') 12 | >>> for file in ls.output(): 13 | ... print file 14 | 'another.txt' 15 | 16 | If you need to extend the behavior, you can also use the ``Shell`` object:: 17 | 18 | >>> from shell import Shell 19 | >>> sh = Shell(has_input=True) 20 | >>> cat = sh.run('cat -u') 21 | >>> cat.write('Hello, world!') 22 | >>> cat.output() 23 | ['Hello, world!'] 24 | 25 | """ 26 | import shlex 27 | import subprocess 28 | import sys 29 | 30 | 31 | __author__ = 'Daniel Lindsley' 32 | __license__ = 'New BSD' 33 | __version__ = (1, 0, 1) 34 | 35 | 36 | class ShellException(Exception): 37 | """The base exception for all shell-related errors.""" 38 | pass 39 | 40 | 41 | class MissingCommandException(ShellException): 42 | """Thrown when no command was setup.""" 43 | pass 44 | 45 | 46 | class CommandError(ShellException): 47 | """Thrown when a command fails.""" 48 | def __init__(self, message, code, stderr): 49 | self.message = message 50 | self.code = code 51 | self.stderr = stderr 52 | super(CommandError, self).__init__(message) 53 | 54 | 55 | class Shell(object): 56 | """ 57 | Handles executing commands & recording output. 58 | 59 | Optionally accepts a ``has_input`` parameter, which should be a boolean. 60 | If set to ``True``, the command will wait to execute until you call the 61 | ``Shell.write`` method & send input. (Default: ``False``) 62 | 63 | Optionally accepts a ``record_output`` parameter, which should be a boolean. 64 | If set to ``True``, the stdout from the command will be recorded. 65 | (Default: ``True``) 66 | 67 | Optionally accepts a ``record_errors`` parameter, which should be a boolean. 68 | If set to ``True``, the stderr from the command will be recorded. 69 | (Default: ``True``) 70 | 71 | Optionally accepts a ``strip_empty`` parameter, which should be a boolean. 72 | If set to ``True``, only non-empty lines from ``Shell.output`` or 73 | ``Shell.errors`` will be returned. (Default: ``True``) 74 | 75 | Optionally accepts a ``die`` parameter, which should be a boolean. 76 | If set to ``True``, raises a CommandError if the command exits with a 77 | non-zero return code. (Default: ``False``) 78 | 79 | Optionally accepts a ``verbose`` parameter, which should be a boolean. 80 | If set to ``True``, prints stdout to stdout and stderr to stderr as 81 | execution happens. (Default: ``False``) 82 | """ 83 | def __init__(self, has_input=False, record_output=True, record_errors=True, 84 | strip_empty=True, die=False, verbose=False): 85 | self.has_input = has_input 86 | self.record_output = record_output 87 | self.record_errors = record_errors 88 | self.strip_empty = strip_empty 89 | self.die = die 90 | self.verbose = verbose 91 | 92 | self.last_command = '' 93 | self.line_breaks = '\n' 94 | self.pid = None 95 | self.code = 0 96 | self._popen = None 97 | self._stdout = '' 98 | self._stderr = '' 99 | 100 | def _split_command(self, command): 101 | """ 102 | Splits a string command into the individual args to pass to ``Popen``. 103 | 104 | If the ``command`` is an array, it is left untouched. 105 | """ 106 | if isinstance(command, (tuple, list)): 107 | return command 108 | 109 | return shlex.split(command) 110 | 111 | def _handle_output(self, stdout, stderr): 112 | """ 113 | Takes stdout/stderr & optionally retains them internally. 114 | 115 | Requires a ``stdout`` parameter, which should either be the output as 116 | a string or ``None``. 117 | 118 | Requires a ``stderr`` parameter, which should either be the errors as 119 | a string or ``None``. 120 | 121 | Records nothing if the ``record_*`` options have been set to ``False``. 122 | """ 123 | if stdout != None: 124 | if self.record_output: 125 | self._stdout += stdout 126 | if self.verbose: 127 | sys.stdout.write(stdout) 128 | sys.stdout.flush() 129 | 130 | if stderr != None: 131 | if self.record_errors: 132 | self._stderr += stderr 133 | if self.verbose: 134 | sys.stderr.write(stderr) 135 | sys.stderr.flush() 136 | 137 | def _communicate(self, the_input=None): 138 | """ 139 | Handles communicating with the process & optionally sends input. 140 | 141 | Optionally accepts a ``the_input`` parameter, which can be a string 142 | to send to the process. (Default: ``None``) 143 | """ 144 | stdout, stderr = self._popen.communicate(input=the_input) 145 | self._handle_output(stdout, stderr) 146 | 147 | if self._popen.returncode is not None: 148 | self.code = self._popen.returncode 149 | 150 | if self.die and self.code != 0: 151 | raise CommandError( 152 | message='Command exited with code {}'.format(self.code), 153 | code=self.code, 154 | stderr=stderr) 155 | 156 | def run(self, command): 157 | """ 158 | Runs a given command. 159 | 160 | Requires a ``command`` parameter should be either a string command 161 | (easier) or an array of arguments to send as the command (if you know 162 | what you're doing). 163 | 164 | Returns the ``Shell`` instance. 165 | 166 | Example:: 167 | 168 | >>> from shell import Shell 169 | >>> sh = Shell() 170 | >>> sh.run('ls -alh') 171 | 172 | """ 173 | self.last_command = command 174 | command_bits = self._split_command(command) 175 | kwargs = { 176 | 'stdout': subprocess.PIPE, 177 | 'stderr': subprocess.PIPE, 178 | 'universal_newlines': True, 179 | } 180 | 181 | if self.has_input: 182 | kwargs['stdin'] = subprocess.PIPE 183 | 184 | self._popen = subprocess.Popen( 185 | command_bits, 186 | **kwargs 187 | ) 188 | self.pid = self._popen.pid 189 | 190 | if not self.has_input: 191 | self._communicate() 192 | 193 | return self 194 | 195 | def write(self, the_input): 196 | """ 197 | If you're working with an interactive process, sends that input to 198 | the process. 199 | 200 | This needs to be used in conjunction with the ``has_input=True`` 201 | parameter. 202 | 203 | Requires a ``the_input`` parameter, which should be a string of the 204 | input to send to the command. 205 | 206 | Returns the ``Shell`` instance. 207 | 208 | Example:: 209 | 210 | >>> from shell import Shell 211 | >>> sh = Shell(has_input=True) 212 | >>> sh.run('cat -u') 213 | >>> sh.write('Hello world!') 214 | 215 | """ 216 | if not self._popen: 217 | raise MissingCommandException( 218 | "No command has been provided. Please call ``run`` first." 219 | ) 220 | 221 | self._communicate(the_input) 222 | return self 223 | 224 | def kill(self): 225 | """ 226 | Kills a given process. 227 | 228 | Example:: 229 | 230 | >>> from shell import Shell 231 | >>> sh = Shell() 232 | >>> sh.run('some_long_running_thing') 233 | >>> sh.kill() 234 | 235 | """ 236 | if not self._popen: 237 | raise MissingCommandException( 238 | "No command has been provided. Please call ``run`` first." 239 | ) 240 | 241 | self._popen.kill() 242 | return self 243 | 244 | def output(self, raw=False): 245 | """ 246 | Returns the output from running a command. 247 | 248 | Optionally accepts a ``raw`` parameter, which should be a boolean. If 249 | ``raw`` is set to ``False``, you get an array of lines of output. If 250 | ``raw`` is set to ``True``, the raw string of output is returned. 251 | (Default: ``False``) 252 | 253 | Example:: 254 | 255 | >>> from shell import Shell 256 | >>> sh = Shell() 257 | >>> sh.run('ls ~') 258 | >>> sh.output() 259 | [ 260 | 'hello.txt', 261 | 'world.txt', 262 | ] 263 | 264 | """ 265 | if raw: 266 | return self._stdout 267 | 268 | lines = self._stdout.split(self.line_breaks) 269 | 270 | if self.strip_empty: 271 | lines = [line for line in lines if line] 272 | 273 | return lines 274 | 275 | def errors(self, raw=False): 276 | """ 277 | Returns the errors from running a command. 278 | 279 | Optionally accepts a ``raw`` parameter, which should be a boolean. If 280 | ``raw`` is set to ``False``, you get an array of lines of errors. If 281 | ``raw`` is set to ``True``, the raw string of errors is returned. 282 | (Default: ``False``) 283 | 284 | Example:: 285 | 286 | >>> from shell import Shell 287 | >>> sh = Shell() 288 | >>> sh.run('ls /there-s-no-way-anyone/has/this/directory/please') 289 | >>> sh.errors() 290 | [ 291 | 'ls /there-s-no-way-anyone/has/this/directory/please: No such file or directory' 292 | ] 293 | 294 | """ 295 | if raw: 296 | return self._stderr 297 | 298 | lines = self._stderr.split(self.line_breaks) 299 | 300 | if self.strip_empty: 301 | lines = [line for line in lines if line] 302 | 303 | return lines 304 | 305 | 306 | def shell(command, has_input=False, record_output=True, record_errors=True, 307 | strip_empty=True, die=False, verbose=False): 308 | """ 309 | A convenient shortcut for running commands. 310 | 311 | Requires a ``command`` parameter should be either a string command 312 | (easier) or an array of arguments to send as the command (if you know 313 | what you're doing). 314 | 315 | Optionally accepts a ``has_input`` parameter, which should be a boolean. 316 | If set to ``True``, the command will wait to execute until you call the 317 | ``Shell.write`` method & send input. (Default: ``False``) 318 | 319 | Optionally accepts a ``record_output`` parameter, which should be a boolean. 320 | If set to ``True``, the stdout from the command will be recorded. 321 | (Default: ``True``) 322 | 323 | Optionally accepts a ``record_errors`` parameter, which should be a boolean. 324 | If set to ``True``, the stderr from the command will be recorded. 325 | (Default: ``True``) 326 | 327 | Optionally accepts a ``strip_empty`` parameter, which should be a boolean. 328 | If set to ``True``, only non-empty lines from ``Shell.output`` or 329 | ``Shell.errors`` will be returned. (Default: ``True``) 330 | 331 | Optionally accepts a ``die`` parameter, which should be a boolean. 332 | If set to ``True``, raises a CommandError if the command exits with a 333 | non-zero return code. (Default: ``False``) 334 | 335 | Optionally accepts a ``verbose`` parameter, which should be a boolean. 336 | If set to ``True``, prints stdout to stdout and stderr to stderr as 337 | execution happens. (Default: ``False``) 338 | 339 | Returns the ``Shell`` instance, which has been run with the given command. 340 | 341 | Example:: 342 | 343 | >>> from shell import shell 344 | >>> sh = shell('ls -alh *py') 345 | >>> sh.output() 346 | ['hello.py', 'world.py'] 347 | 348 | """ 349 | sh = Shell( 350 | has_input=has_input, 351 | record_output=record_output, 352 | record_errors=record_errors, 353 | strip_empty=strip_empty, 354 | die=die, 355 | verbose=verbose 356 | ) 357 | return sh.run(command) 358 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import mock 2 | import os 3 | import shutil 4 | import subprocess 5 | 6 | try: 7 | import unittest2 as unittest 8 | except ImportError: 9 | import unittest 10 | 11 | from shell import CommandError, Shell, shell 12 | 13 | 14 | class ShellTestCase(unittest.TestCase): 15 | def setUp(self): 16 | super(ShellTestCase, self).setUp() 17 | self.test_dir = os.path.join('/tmp', 'python_shell') 18 | self.hello_path = os.path.join(self.test_dir, 'hello.txt') 19 | self.sh = Shell() 20 | 21 | shutil.rmtree(self.test_dir, ignore_errors=True) 22 | os.makedirs(self.test_dir) 23 | 24 | def tearDown(self): 25 | shutil.rmtree(self.test_dir) 26 | super(ShellTestCase, self).tearDown() 27 | 28 | def test_initialization(self): 29 | sh = Shell() 30 | self.assertFalse(sh.has_input) 31 | self.assertTrue(sh.record_output) 32 | self.assertTrue(sh.record_errors) 33 | self.assertEqual(sh.last_command, '') 34 | self.assertEqual(sh.line_breaks, '\n') 35 | self.assertEqual(sh.code, 0) 36 | self.assertEqual(sh._popen, None) 37 | 38 | sh = Shell(has_input=True, record_output=False, record_errors=False) 39 | self.assertTrue(sh.has_input) 40 | self.assertFalse(sh.record_output) 41 | self.assertFalse(sh.record_errors) 42 | 43 | def test__split_command(self): 44 | self.assertEqual(self.sh._split_command('ls'), ['ls']) 45 | self.assertEqual(self.sh._split_command('ls -alh *.py'), ['ls', '-alh', '*.py']) 46 | self.assertEqual(self.sh._split_command(['ls', '-alh']), ['ls', '-alh']) 47 | 48 | def test__handle_output_simple(self): 49 | sh = Shell() 50 | self.assertEqual(sh._stdout, '') 51 | self.assertEqual(sh._stderr, '') 52 | 53 | sh._handle_output('another.txt\n', None) 54 | self.assertEqual(sh._stdout, 'another.txt\n') 55 | self.assertEqual(sh._stderr, '') 56 | 57 | sh._handle_output('something.txt\n', 'Error: Please supply an arg.\n') 58 | self.assertEqual(sh._stdout, 'another.txt\nsomething.txt\n') 59 | self.assertEqual(sh._stderr, 'Error: Please supply an arg.\n') 60 | 61 | def test__handle_output_norecord(self): 62 | sh = Shell(record_output=False, record_errors=False) 63 | self.assertEqual(sh._stdout, '') 64 | self.assertEqual(sh._stderr, '') 65 | 66 | sh._handle_output('another.txt\n', 'Error: Please supply an arg.') 67 | self.assertEqual(sh._stdout, '') 68 | self.assertEqual(sh._stderr, '') 69 | 70 | def test__communicate(self): 71 | def fake_communicate(input=None): 72 | self.sh._popen.returncode = 1 73 | return ('whatever\n', 'An error') 74 | 75 | self.assertEqual(self.sh._stdout, '') 76 | self.assertEqual(self.sh._stderr, '') 77 | self.assertEqual(self.sh.code, 0) 78 | self.sh._popen = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 79 | 80 | with mock.patch.object(self.sh._popen, 'communicate', fake_communicate) as mock_communicate: 81 | self.sh._communicate() 82 | self.assertEqual(self.sh._stdout, 'whatever\n') 83 | self.assertEqual(self.sh._stderr, 'An error') 84 | self.assertEqual(self.sh.code, 1) 85 | self.assertNotEqual(self.sh.pid, 0) 86 | 87 | def test_run(self): 88 | self.assertFalse(os.path.exists(self.hello_path)) 89 | 90 | self.sh.run('touch %s' % self.hello_path) 91 | self.assertTrue(os.path.exists(self.hello_path)) 92 | self.assertEqual(self.sh.code, 0) 93 | 94 | def test_stdout(self): 95 | with open(os.path.join(self.test_dir, 'another.txt'), 'w') as another: 96 | another.write('Whatev.') 97 | 98 | self.sh.run('ls %s' % self.test_dir) 99 | self.assertEqual(self.sh.code, 0) 100 | self.assertEqual(self.sh.output(), ['another.txt']) 101 | 102 | # Now with the raw output. 103 | self.assertEqual(self.sh.output(raw=True), 'another.txt\n') 104 | 105 | def test_stderr(self): 106 | self.sh.run('ls /there-s-no-way-anyone/has/this/directory/please') 107 | self.assertEqual(self.sh.code, 1) 108 | self.assertTrue('No such file' in self.sh.errors()[0]) 109 | 110 | # Now with the raw errors. 111 | self.assertTrue('No such file' in self.sh.errors(raw=True)) 112 | 113 | def test_write(self): 114 | sh = Shell(has_input=True) 115 | sh.run('cat -u') 116 | sh.write('TEH INPUTS') 117 | self.assertEqual(sh.output(), ['TEH INPUTS']) 118 | self.assertEqual(sh.code, 0) 119 | 120 | # TODO: This test is flawed. Not sure how to implement it with kill. 121 | # def test_kill(self): 122 | # spin = subprocess.Popen('sleep 10 && echo "done" &', stdout=subprocess.PIPE) 123 | # spin.poll() 124 | # 125 | # self.sh._popen = spin 126 | # 127 | # self.sh.kill() 128 | # self.assertEqual(self.sh.code, 1) 129 | 130 | def test_shortcut_interface(self): 131 | self.assertFalse(os.path.exists(self.hello_path)) 132 | 133 | sh = shell('touch %s' % self.hello_path) 134 | self.assertTrue(os.path.exists(self.hello_path)) 135 | self.assertEqual(sh.code, 0) 136 | 137 | def test_chaining(self): 138 | sh = Shell(has_input=True) 139 | output = sh.run('cat -u').write('Hello, world!').output() 140 | self.assertEqual(output, ['Hello, world!']) 141 | 142 | output = shell('cat -u', has_input=True).write('Hello, world!').output() 143 | self.assertEqual(output, ['Hello, world!']) 144 | 145 | def test_die(self): 146 | sh = Shell(die=True) 147 | with self.assertRaises(CommandError): 148 | sh.run('ls /maybe/this/exists/on/windows/or/something/idk') 149 | try: 150 | no_die = shell('ls /other/fake/stuff/for/sure') # get the stderr 151 | sh.run('ls /other/fake/stuff/for/sure') 152 | except CommandError, e: 153 | self.assertEqual(e.code, 1) 154 | self.assertEqual(e.stderr, no_die.errors()[0] + os.linesep) 155 | 156 | def test_verbose(self): 157 | sh = Shell(verbose=True) 158 | with mock.patch('shell.sys.stdout') as mock_stdout: 159 | sh.run('ls') 160 | mock_stdout.write.assert_called_once_with(os.linesep.join(sh.output()) + os.linesep) 161 | with mock.patch('shell.sys.stderr') as mock_stderr: 162 | sh.run('ls /total/garbage/not/real/stuff') 163 | mock_stderr.write.assert_called_once_with(os.linesep.join(sh.errors()) + os.linesep) 164 | 165 | 166 | --------------------------------------------------------------------------------