Saravanan666/pypi-org huggingface dataset:
Package: shell.py
Bring the good part of Shell scripting to Python.Install$pipinstallshell.pyUsageExecute a shell commandBlock until return:>>>fromshellimportex>>>ex('echo hello shell.py').stdout()'hello shell.py\n'Asynchronous execution:>>>fromshellimportex>>>c=asex('echo hello shell.py')>>># do something else...>>>c.stdout()# wait until process exit and read stdout'hello shell.py\n'Pipe commandsfromshellimportexre=(ex("ifconfig")|"grep -A 1 eth0"|"grep inet"|"awk '{print $2}'"|"cut -d: -f 2").stdout()Orfromshellimportpipe_allpipe_all(["ls -la ~","awk '{print $9}'","grep -E '^\.'","wc -l"]).stdout()Use string as stdin>>>fromshellimportinstream>>>instream("1 2 3").p("awk '{print $1}'").stdout()'1\n'This is equivalent to:>>>fromshellimportex>>>ex("echo 1 2 3").p("awk '{print $1}'").stdout()IO redirectOverwrite a file:>>>fromshellimportex>>>ex('echo yolo').wr('/tmp/out')>>>ex('echo yolo')>'/tmp/out'Append to a file:>>>fromshellimportex>>>ex('echo yolo').ap('/tmp/out')>>>ex('echo yolo')>>'/tmp/out'Run commands in parallelBlock until all commands return:>>>fromshellimportparallelaspar>>>par.ex_all(['sleep 2','sleep 2'])# return in 2sAsynchronous parallel execution:>>>fromshellimportparallelaspar>>>pe=par.asex_all(['sleep 2','sleep 2'])# return immediately>>># do something else...>>>pe.wait()Set working directorySet the directory in which the commands are executed:>>>withshell.cwd('~/server/data/upload/')asold_path:>>>shell.ex('find ./images -name "*.png"')|'minify ./public'>>'upload.log'This is equivalent to:>>>shell.ex('find ~/server/data/upload/images -name "*.png"')|'minify ~/server/data/upload/public'>>'~/server/data/upload.log'See test cases for more examples.TestsRun tests with nosetests(at least v1.3.0):$maketest
Package: shell-pype
# command line tool #Use like this:cat data.tsv | cut -c4,9 | py “print(‘DELETE FROM sites WHERE id IN ({0})’.format(‘,’.join(IN)))” | psql testdb adminWhere thepybit replaces the slightly longer command:python -c “import sys; print ‘DELETE FROM sites WHERE id IN ({0})’.format(‘,’.join(sys.stdin))”I made this because I am tired of reading man pages forawkandsedand others; I already know python, but I am also tired of typingimport sys, etc repeatedly.os,sys,csvandjsonare pre-imported, as well asunicode_literalsandprint_functionfrom the future.Aditionally the following are imported and renamed:sys.stdin -> IN
sys.stdout -> OUT
functools -> FT
itertools -> IT
operator -> OP
pprint.pprint -> PPFor those interested in more robust solutions checkout <a href=’https://github.com/alecthomas/pawk’>pawk</a> or <a href=’http://code.google.com/p/pyp/’>pyp</a>.
Package: shellrecharge
Python: Shell RechargePython 3 package to retrieve public EV charger data from Shell RechargeAboutThis package allows you to request data from public EV chargers using Shell Recharge.
I build it to create a home-assistant integration, it can be done with rest calls only, but then options are limited.Installationpip3installshellrechargeDevelopmentTo create a development environment to commit code.pip3 install pdm
pip3 install ruff
pdm init

sudo apt install pre-commit
pip3 install pre-commitRun checks before PR/Commit:make allExampleBelow provides example on how to use the library.#!/usr/bin/env python3
"""Example code."""
import asyncio
import logging
import sys
from asyncio import CancelledError

import aiohttp
from aiohttp.client_exceptions import ClientError

import shellrecharge
from shellrecharge import LocationEmptyError, LocationValidationError


async def main():
    """Main module."""

    # Some random stations
    location_ids = ["9b9428ab-1dfd-4230-a024-084eacf776ff", "682154", "9cf6c16b-b043-4ba8-b7ca-872f82a0faf4"]

    async with aiohttp.ClientSession() as session:
        try:
            api = shellrecharge.Api(session)
            for location_id in location_ids:
                location = await api.location_by_id(location_id)
                logging.info(location)
        except LocationEmptyError:
            logging.error("No data returned, check location id")
        except LocationValidationError as err:
            logging.error("Location validation error {}" % err)
        except (ClientError, TimeoutError, CancelledError) as err:
            logging.error(err)


if __name__ == "__main__":
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    loop = asyncio.new_event_loop()
    loop.run_until_complete(main())Donations
Package: shellrun
Look atenvoyfirst.envoy.run(command)waits for completion
before returning output, which is not what you need when wrapping long
running tools, where output needed as soon as it appears,shellrun.run(command)does not intercept output - there is a
separate command for that.>>> import shellrun
>>> r = shellrun.run('uptime')
 04:06:37 up 2 min,  1 user,  load average: 0.20, 0.19, 0.08
>>> r.output
>>> r.success
True
>>> r.retcode
0To capture outputenvoy-style, userun_capture.stdoutandstderrare merged, because that’s
how users see it:>>> r = shellrun.run_capture('uptime')
>>> r.output
' 04:07:16 up 2 min,  1 user,  load average: 0.11, 0.17, 0.08\n'
>>> r.success
True
>>> r.retcode
0Quick comparison of result objects:envoy.Responseshellrun.Result.command.command.status_code.retcode.success.output.std_out.std_errExample of.successusage:from shellrun import run_capture

r = run_capture('ls -la')
if r.success:
    print(r.output)
else:
    print("Error: '%s' exit code %s" % (r.command, r.retcode))
    print("         ...")
    # print last three lines of output
    for line in r.output.splitlines()[-3:]:
        print("       %s" % line)
Package: shell-scripting
#!/usr/bin/env python3.7

from shell_scripting import run, shell, shell_list

run("date | sed s/2018/2019/ > test.out")

print(shell("env | grep USER").stdout.split("\n"))

print(shell("cat /root/file"))

r = shell("cat /root/file")
print(
    f"""\
    args: {r.args}
    returncode: {r.returncode}
    stdout: {r.stdout}
    stderr: {r.stderr}\
""",
    end="",
)

for x in shell_list("env"):
    print(x)
Package: shellshock
Write and test your shell scripts using PythonShell scripts are great - they run on most *nix machines, they allow you interact with the file system easily, and they are light weight and don't require a massive runtime. However, the syntax is error prone and they are difficult to manage and test. Shellshock lets you write and test your shell scripts using the Python syntax and test cases you already know and love.InstallationWriting with Shellshock requires Python. The shell scripts it outputs do not require Python to run though.pipinstallshellshockUsageTo convert a Python shellshock script to a regular shell script:shellshockmy_script.py-omy_script.shStarting with an existing shell scriptLet's say you have an existing shell script you want to convert that looks like this:oldscript.shif[-f"file"];thenecho"ok"fiYou can easily make this a shellshock script using thess.shellmethod and a multiline string at the top of the file:oldscript.pyimportshellshockasssss.shell("""if [ -f "file" ]; thenecho "ok"fi""")Then you could convert it to full Python shellscript syntax like so:newscript.pyimportshellshockasssifss.isfile("file"):print("ok")
Package: shellsnmp
Shamelessly (ab)using NET-SNMP shell commands for a quick-and-dirty Python SNMP libWhyI’m not fond of thepySNMPAPIsnimpyrequires loading libffi-dev and libsmi-dev (i.e. root privs) on the systemIt’s fast enoughUsageBe sure you have MIB files loaded on your system. You can download them from
Cisco’s FTP site like this…wgetftp://ftp.cisco.com/pub/mibs/v2/MIB-NAME.myfrom shellsnmp.Poller import SNMP

snmp = SNMP(community='public', host='172.16.1.3')
status, time = snmp.bulkwalk(mibfile='/path/to/IF-MIB.my',
    oidspec='ifOperStatus')Note that onlybulkwalk()has been implemented at this time.Installationpip install shellsnmpLicense and CopyrightLicensed MITCopyright 2016 - David Michael Pennington (mike [~at~] pennington [/dot] net)
Package: shell-source
python-shell-sourceA python module for sourcing variables from shell scripts.InstallationYou can install this package with pip or conda.$pipinstallshell-source$condainstall-cabrahammurcianoshell-sourceDocumentationThe full documentation is availablehereUsageThis module provides a functionsourcewhich attempts to mimic the shell's source command.The purpose of this function is to allow you to run a shell script which sets either environment variables or local variables, and then give you access to those variables. Normally this is not a straght-forward task, but this function achieves it by running the script in its intended shell then injecting commands to the shell to write its local variables and its environment variables to a temporary file. Finally it reads the temporary file and parses it to return to you with exactly the data you asked for.Basic UsageIf you just pass a script and an interpreter you'll get back all the environment variables and local variables visible to and set by the script.>>>fromshell_sourceimportsource>>>variables=source("path/to/script.sh","bash")>>># It returns a dictionary of local and environment variables known by the script.>>>variables{"USER":"abraham","PATH":"/bin:/usr/bin",...,"foo":"bar"}Requesting Specific VariablesIf you specify the argumentvariables, then only those variables you passed will be present as keys in the returned dictionary.>>>source("path/to/script.sh","zsh",variables=("foo","bar","biz")){"foo":...,"bar":...,"biz",...}Ignoring Local VariablesIf you don't want to obtain any local variables set by the script, but only want the environment variables, you can passignore_locals=True.Passing Arguments to the shellIf you want to pass arguments to the shell, for example-xor-e, you can pass it directly in theshellargument.>>>source("path/to/script.sh","bash -x")Passing Arguments to the scriptIf you want to pass arguments to the script being sourced, you can pass them in theargsargument.>>>source("path/to/script.sh","bash",args=("foo","bar"))Supporting Different ShellsThis module has been tested to work withbash,zsh, andkshout of the box. You can use any other shell that's somewhat posix compliant, but it it doesn't work, you may have to create a class derived from theScripterclass to indicate tosourcehow to interact with the shell you want to use.Some specialized implementations ofScripterare provided inshell_source.scriptersfor shells that are not posix compliant, such ascsh,tcshandfish.For example, to usetcshto source a script, you can use theCshScripterclass like so:>>>source("path/to/script.csh","tcsh",scripter=CshScripter())
Package: shellstats
Shellstats reads your shell history and shows you the most used
commands. Typical output looks like:Command              Count      Percentage
 1 ls                   326        17.0%
 2 cd                   254        13.3%
 3 less                 172        8.99%
 4 sudo                 162        8.47%
 5 emacs                159        8.31%
 6 screen               146        7.63%
 7 echo                 103        5.38%
 8 top                  100        5.23%
 9 du                   85         4.44%
10 grep                 70         3.66%InstallationInstall it with a simple:$ pip install shellstatsIn addition if you want to see a pie chart of the above output, you need
to have matplotlib installed (package ‘python-matplotlib’ in
Debian/Ubuntu/Fedora).UsageUsage: shellstats [OPTIONS]

  Print the most frequently used shell commands.

Options:
  --n INTEGER          How many commands to show.
  --plot               Plot command usage in pie chart.
  --command TEXT       Most frequent subcommands for command, e.g. sudo, git.
  --history-file PATH  Read shell history from history-file.
  --shell TEXT         Specify shell history format: bash, fish or zsh.
  --help               Show this message and exit.
Package: shellstream
# shellstream
> Version 0.0.1# What is it?shellstream is a python client that pipes your terminal IO to the web:# To Install## pip makes it easypip install shellstream# To RunTo run StreamShell, you will need to receive an API Token from [coming soon].  To retrieve a token, first sign up for the service (it’s free) and then head to this page [coming soon].Add this token to your.bash_profile:`bash STREAM_SHELL_TOKEN = [your token] `# MotivationWhen you’ve got an issue at the command line and need help online, copy and pasting your session on an ongoing basis is a pain and it makes you switch mental context.  So, I created shellstream along with the companion website to make debugging smoother.# LimitationsThis initial version is naive.  It is not cross-platform at this point, depending on a number of unix commands. That will come with time.
Package: shellstreaming
A stream processor working with shell commandsTutorialFor developersAPI referenceBuilding and uploading documentsTestingUploading packages to PyPIThanksTutorialSeehttp://packages.python.org/shellstreaming/tutorial.htmlFor developersAPI referenceSphinx-powered documents are available onhttp://packages.python.org/shellstreamingBuilding and uploading documents$./setup.pybuild_sphinx$browserdoc/html/index.html$./setup.pyupload_sphinxTesting$./setup.pynosetests$browserhtmlcov/index.html# check coverageSome tests depend too much on personal configuration;
one needs Twitter OAuth info and another needs access to remote machine viassh.
To enable all of these tests, comment out the line starts withignore-filesinsetup.cfgand runnosetestsagain.Uploading packages to PyPI$emacssetup.py# edit `version` string$emacsCHANGES.txt$./setup.pysdistuploadOr usezest.releaser, a convenient tool for repeated release cycles.Thanksmodocachefor a few pull requests!
Package: shellt
A sample Python projectA sample project that exists as an aid to thePython Packaging User
Guide'sTutorial on Packaging and Distributing
Projects.This project does not aim to cover best practices for Python project
development as a whole. For example, it does not provide guidance or tool
recommendations for version control, documentation, or testing.The source for this project is available here.The metadata for a Python project is defined in thepyproject.tomlfile,
an example of which is included in this project. You should edit this file
accordingly to adapt this sample project to your needs.This is the README file for the project.The file should use UTF-8 encoding and can be written usingreStructuredTextormarkdownwith the appropriatekey set. It will be used to generate the project webpage on PyPI and will be
displayed as the project homepage on common code-hosting services, and should be
written for that purpose.Typical contents for this file would include an overview of the project, basic
usage examples, etc. Generally, including the project changelog in here is not a
good idea, although a simple “What's New” section for the most recent version
may be appropriate.
Package: shell-themer
shell-themerThere are many modern *nix and *bsd command line tools which can output
using a full 16.7 million color palette. For example:fzfdustbatgumEven the venerablelscan show various types of files in different colors.Unfortunately, these tools all use slightly different color configuration mechanisms.
With enough fiddling, you can get your shell init scripts to make all these tools
use a similar color scheme, but if you want to change it, you've got a lot of work
ahead.shell-themeruses a single theme configuration file to standardize and unify
a set of color configurations, and generates the shell code to implement those
changes.All that hand tweaking in your shell init files can now be replaced with:export THEME_FILE=~/themes/dracula.toml
source <(shell-themer generate)This changes all your environment variables and other settings for the many
shell tools you use to reflect the colors in the theme you have specified.InstallationYou'll need python version 3.7 or higher. Install with pip:pip install shell_themerYou need a *nix-ish bash shell environment. Probably works in Windows Subsystem
for Linux, but isn't tested there.
Package: shellting
shelltingAugment shell scripts with Python.DescriptionDocumentation still to be done.DevelopmentAssuming you usepyenvandpyenv-virtualenvfor development, here's how to setup a 'shellting' development environment manually:pyenv install 3.7.3
pyenv virtualenv 3.7.3 shellting
git clone https://gitlab.com/frkl/shellting
cd <shellting_dir>
pyenv local shellting
pip install -e .[develop,testing,docs]
pre-commit installCopyright & licensePlease check theLICENSEfile in this repository (it's a short license!), also check out thefreckleslicense pagefor more details.Parity Public License 6.0.0Copyright (c) 2019 frkl OÜ
Package: shellu
Shell UtilitiesThe projectshell-utilitiesis a set of scripts to use ANSI characters to modify the shell output.MessagesMessagesThis module provide a class to management the shell output from the program. Is posible enable or disable different types of messages and provide a style with ANSI codes, is posible disable this function also.Exampleimportsysimportargparsefromshellu.messagesimport*mw=MessageWriter.getInstance()defwriteInformation(message:str):mw.writeMessage(message=message)defwriteError(message:str):mw.writeMessage(message=message,messagetype=MessageType.ERROR,foregroundcolor=ForegroundColor.RED)defwriteVerbose(message:str):mw.writeMessage(message=message,messagetype=MessageType.VERBOSE,backgroundcolor=BackgroundColor.BLACK,foregroundcolor=ForegroundColor.YELLOW,displaymode=DisplayMode.BOLD)defwriteDebug(message:str):mw.writeMessage(message=message,messagetype=MessageType.DEBUG,foregroundcolor=ForegroundColor.PURPLE)defwriteWarning(message:str):mw.writeMessage(message=message,messagetype=MessageType.WARNING,backgroundcolor=BackgroundColor.YELLOW,foregroundcolor=ForegroundColor.RED,displaymode=DisplayMode.NEGATIVE2)defargumentsParser(args):parser=argparse.ArgumentParser(description="Test script")parser.add_argument('-v','--verbose',dest='verbose',action='store_true',help='Enable the verbose messages')parser.add_argument('--debug',dest='debug',action='store_true',help='Enable the debug messages')parser.add_argument('--no-warning',dest='nowarning',action='store_true',help='Disable the warning messages')parser.add_argument('--no-ansi-codes',dest='noansicodes',action='store_true',help='Disable the warning messages')returnparser.parse_args(args=args)defmain():arguments=argumentsParser(sys.argv[1:])mw.setVerbose(arguments.verbose)mw.setDebug(arguments.debug)mw.setWarning(notarguments.nowarning)mw.setANSICode(notarguments.noansicodes)writeInformation("This is a information message")writeVerbose("This is a verbose message")writeDebug("This is a debug message")writeWarning("This is a warning message")if__name__=='__main__':main()Required version3.7
Package: shellvaluepy
pip3 install shellvaluepy#inputfromshellvaluepy.infoimportshellshell.value('dir')#outputXXXXXXXXXXXXXXXXXXXXXXXXXXXX#inputfromshellvaluepy.infoimportshellshell.install('shell_value')#outputOKtoinstall!orerror!
Package: shellvars
Homepage:Shellvars HomepageDownload:Shellvars on PyPIDocumentation:Shellvars DocsLicense:MIT LicenseSupport:Mailing list (testing-in-python@lists.idyll.org)Issue tracker:Github IssuesBuild status:ShellvarsA Python interpreter for shell variable expressions.shellvars supports Python 2.6 and up, and should support Jython etc as well.The following expressions are supported:$NAME${NAME}${NAME:-REPLACEMENT}${NAME-REPLACEMENT}${NAME:=REPLACEMENT}${NAME=REPLACEMENT}${NAME:?[ERRORMSG]}${NAME?[ERRORMSG]}${NAME:+REPLACEMENT}${NAME+REPLACEMENT}Recursive expressions are supported too. For instance:>>> from shellvars import evaluate
>>> evaluate('${foo:-${bar:=baz}}', {})
('baz', {'bar': 'baz'})For details on shell variable syntax, consult your shell or Posix
documentation.UsageTo evaluate an expression callevaluatewith the expression and any
variables you want available to the expression. Variables keys and values must
both be strings.  Variables that are missing from your variable dict are
considered ‘unset’ in shell terms.The return is an evaluated string and any variable assignments performed
by the expression.Preserving unset expressionsshellvars has a special mode where expressions that are for unset variables
are preserved rather than evaluated. This permits passing them onto a real
shell to interpret without needing special quoting from the user. For
instance:>>> from shellvars import SKIP
>>> evaluate('$foo $bar', {'foo': 'baz'}, absent=SKIP)
('baz $bar', {})InstallationUse pip to install:pip install shellvarsDevelopmentInstall the test dependencies via pip:pip install .[test]Push up changes as PR’s to the GitHubrepository.Bug trackerUse the GitHubissue tracker.ReleasingUse semver for version decisions.To release:Tag the repo e.g. 1.2.3Build a signed sdist and wheelUpload to PyPICopyrightCopyright (c) 2015 Robert Collins <robertc@robertcollins.net>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.
Package: shellvars-py
Read environment variables defined in a shell script into Python.
This library uses the shell to get variable values, and handles
multiline variables.# UsageGiven a shell file: myvars.env:`shell#!/bin/bashexport VAR1=1 exportVAR2="Thisis a multiline value" export VAR3=3 NOT_EXPORTED=4 `## get_vars`python >>> import shellvars >>>shellvars.get_vars('myvars.env'){'VAR1': '1', 'VAR2': 'This\nis\na\nmultiline value', 'VAR3': '3' } `## list_vars
Lists the variable names in the script.`python >>> import shellvars >>>shellvars.list_vars('myvars.env')['VAR1', 'VAR2', 'VAR3'] `This is equivalent to, but faster than`python >>>shellvars.get_vars('myvars.env').keys()`
Package: shellwhat
shellwhatshellwhatenables you to write Submission Correctness Tests (SCTs) for interactive Shell exercises on DataCamp.If you are new to teaching on DataCamp, check outhttps://instructor-support.datacamp.com.If you want to learn what SCTs are and how they work, visitthis articlespecifically.For a complete overview of all functionality insideshellwhatand articles about what to use when, consulthttps://shellwhat.readthedocs.io.Installingpip install shellwhatDevelopmentBy default, theDummyParseris used, that does not parse the shell code.
Hence, you can not run tests that need this parser:pytest -m "not osh"If you also want to run these 'parser tests',
there is Dockerfile to parse shell commands with
theOil parser:# Look in Makefile for details
export SHELLWHAT_PARSER='docker'
make testLicense
Package: shellwhat-ext
shellwhat_extExtensions toshellwhattesting.Including in a DataCamp courseIn the course'srequirements.sh, add# replace 0.0.1 with the appropriate release version
pip3 install --no-deps shellwhat-ext==0.0.1To use the extensions in an exercise's SCT, import the function you want into the SCT block of the exercise:fromshellwhat_extimporttest_cmdlineEx()>>test_cmdline([['wc','l','+']])Deploying to PyPIFollow these stepsOpen a PR, merge into master when appropriate.Once merged, increment__version__ = 0.0.1to reflect changes (see semver for guidance).Create a github release labeledvVERSION. E.g.v0.0.1. (seehere).Running testsmake install
make test