Delete .venv directory
This commit is contained in:
parent
151fe66525
commit
18ffd4ab4d
@ -1,241 +0,0 @@
|
||||
<#
|
||||
.Synopsis
|
||||
Activate a Python virtual environment for the current PowerShell session.
|
||||
|
||||
.Description
|
||||
Pushes the python executable for a virtual environment to the front of the
|
||||
$Env:PATH environment variable and sets the prompt to signify that you are
|
||||
in a Python virtual environment. Makes use of the command line switches as
|
||||
well as the `pyvenv.cfg` file values present in the virtual environment.
|
||||
|
||||
.Parameter VenvDir
|
||||
Path to the directory that contains the virtual environment to activate. The
|
||||
default value for this is the parent of the directory that the Activate.ps1
|
||||
script is located within.
|
||||
|
||||
.Parameter Prompt
|
||||
The prompt prefix to display when this virtual environment is activated. By
|
||||
default, this prompt is the name of the virtual environment folder (VenvDir)
|
||||
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
|
||||
|
||||
.Example
|
||||
Activate.ps1
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -Verbose
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script,
|
||||
and shows extra information about the activation as it executes.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
|
||||
Activates the Python virtual environment located in the specified location.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -Prompt "MyPython"
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script,
|
||||
and prefixes the current prompt with the specified string (surrounded in
|
||||
parentheses) while the virtual environment is active.
|
||||
|
||||
.Notes
|
||||
On Windows, it may be required to enable this Activate.ps1 script by setting the
|
||||
execution policy for the user. You can do this by issuing the following PowerShell
|
||||
command:
|
||||
|
||||
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
||||
|
||||
For more information on Execution Policies:
|
||||
https://go.microsoft.com/fwlink/?LinkID=135170
|
||||
|
||||
#>
|
||||
Param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[String]
|
||||
$VenvDir,
|
||||
[Parameter(Mandatory = $false)]
|
||||
[String]
|
||||
$Prompt
|
||||
)
|
||||
|
||||
<# Function declarations --------------------------------------------------- #>
|
||||
|
||||
<#
|
||||
.Synopsis
|
||||
Remove all shell session elements added by the Activate script, including the
|
||||
addition of the virtual environment's Python executable from the beginning of
|
||||
the PATH variable.
|
||||
|
||||
.Parameter NonDestructive
|
||||
If present, do not remove this function from the global namespace for the
|
||||
session.
|
||||
|
||||
#>
|
||||
function global:deactivate ([switch]$NonDestructive) {
|
||||
# Revert to original values
|
||||
|
||||
# The prior prompt:
|
||||
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
|
||||
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
|
||||
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
|
||||
}
|
||||
|
||||
# The prior PYTHONHOME:
|
||||
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
|
||||
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
|
||||
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
|
||||
}
|
||||
|
||||
# The prior PATH:
|
||||
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
|
||||
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
|
||||
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
|
||||
}
|
||||
|
||||
# Just remove the VIRTUAL_ENV altogether:
|
||||
if (Test-Path -Path Env:VIRTUAL_ENV) {
|
||||
Remove-Item -Path env:VIRTUAL_ENV
|
||||
}
|
||||
|
||||
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
|
||||
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
|
||||
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
|
||||
}
|
||||
|
||||
# Leave deactivate function in the global namespace if requested:
|
||||
if (-not $NonDestructive) {
|
||||
Remove-Item -Path function:deactivate
|
||||
}
|
||||
}
|
||||
|
||||
<#
|
||||
.Description
|
||||
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
|
||||
given folder, and returns them in a map.
|
||||
|
||||
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
|
||||
two strings separated by `=` (with any amount of whitespace surrounding the =)
|
||||
then it is considered a `key = value` line. The left hand string is the key,
|
||||
the right hand is the value.
|
||||
|
||||
If the value starts with a `'` or a `"` then the first and last character is
|
||||
stripped from the value before being captured.
|
||||
|
||||
.Parameter ConfigDir
|
||||
Path to the directory that contains the `pyvenv.cfg` file.
|
||||
#>
|
||||
function Get-PyVenvConfig(
|
||||
[String]
|
||||
$ConfigDir
|
||||
) {
|
||||
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
|
||||
|
||||
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
|
||||
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
|
||||
|
||||
# An empty map will be returned if no config file is found.
|
||||
$pyvenvConfig = @{ }
|
||||
|
||||
if ($pyvenvConfigPath) {
|
||||
|
||||
Write-Verbose "File exists, parse `key = value` lines"
|
||||
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
|
||||
|
||||
$pyvenvConfigContent | ForEach-Object {
|
||||
$keyval = $PSItem -split "\s*=\s*", 2
|
||||
if ($keyval[0] -and $keyval[1]) {
|
||||
$val = $keyval[1]
|
||||
|
||||
# Remove extraneous quotations around a string value.
|
||||
if ("'""".Contains($val.Substring(0, 1))) {
|
||||
$val = $val.Substring(1, $val.Length - 2)
|
||||
}
|
||||
|
||||
$pyvenvConfig[$keyval[0]] = $val
|
||||
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
|
||||
}
|
||||
}
|
||||
}
|
||||
return $pyvenvConfig
|
||||
}
|
||||
|
||||
|
||||
<# Begin Activate script --------------------------------------------------- #>
|
||||
|
||||
# Determine the containing directory of this script
|
||||
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||
$VenvExecDir = Get-Item -Path $VenvExecPath
|
||||
|
||||
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
|
||||
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
|
||||
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
|
||||
|
||||
# Set values required in priority: CmdLine, ConfigFile, Default
|
||||
# First, get the location of the virtual environment, it might not be
|
||||
# VenvExecDir if specified on the command line.
|
||||
if ($VenvDir) {
|
||||
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
|
||||
}
|
||||
else {
|
||||
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
|
||||
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
|
||||
Write-Verbose "VenvDir=$VenvDir"
|
||||
}
|
||||
|
||||
# Next, read the `pyvenv.cfg` file to determine any required value such
|
||||
# as `prompt`.
|
||||
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
|
||||
|
||||
# Next, set the prompt from the command line, or the config file, or
|
||||
# just use the name of the virtual environment folder.
|
||||
if ($Prompt) {
|
||||
Write-Verbose "Prompt specified as argument, using '$Prompt'"
|
||||
}
|
||||
else {
|
||||
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
|
||||
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
|
||||
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
|
||||
$Prompt = $pyvenvCfg['prompt'];
|
||||
}
|
||||
else {
|
||||
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virutal environment)"
|
||||
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
|
||||
$Prompt = Split-Path -Path $venvDir -Leaf
|
||||
}
|
||||
}
|
||||
|
||||
Write-Verbose "Prompt = '$Prompt'"
|
||||
Write-Verbose "VenvDir='$VenvDir'"
|
||||
|
||||
# Deactivate any currently active virtual environment, but leave the
|
||||
# deactivate function in place.
|
||||
deactivate -nondestructive
|
||||
|
||||
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
|
||||
# that there is an activated venv.
|
||||
$env:VIRTUAL_ENV = $VenvDir
|
||||
|
||||
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
|
||||
|
||||
Write-Verbose "Setting prompt to '$Prompt'"
|
||||
|
||||
# Set the prompt to include the env name
|
||||
# Make sure _OLD_VIRTUAL_PROMPT is global
|
||||
function global:_OLD_VIRTUAL_PROMPT { "" }
|
||||
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
|
||||
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
|
||||
|
||||
function global:prompt {
|
||||
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
|
||||
_OLD_VIRTUAL_PROMPT
|
||||
}
|
||||
}
|
||||
|
||||
# Clear PYTHONHOME
|
||||
if (Test-Path -Path Env:PYTHONHOME) {
|
||||
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
|
||||
Remove-Item -Path Env:PYTHONHOME
|
||||
}
|
||||
|
||||
# Add the venv to the PATH
|
||||
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
|
||||
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
|
@ -1,66 +0,0 @@
|
||||
# This file must be used with "source bin/activate" *from bash*
|
||||
# you cannot run it directly
|
||||
|
||||
deactivate () {
|
||||
# reset old environment variables
|
||||
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
|
||||
PATH="${_OLD_VIRTUAL_PATH:-}"
|
||||
export PATH
|
||||
unset _OLD_VIRTUAL_PATH
|
||||
fi
|
||||
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
|
||||
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
|
||||
export PYTHONHOME
|
||||
unset _OLD_VIRTUAL_PYTHONHOME
|
||||
fi
|
||||
|
||||
# This should detect bash and zsh, which have a hash command that must
|
||||
# be called to get it to forget past commands. Without forgetting
|
||||
# past commands the $PATH changes we made may not be respected
|
||||
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
|
||||
hash -r 2> /dev/null
|
||||
fi
|
||||
|
||||
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
|
||||
PS1="${_OLD_VIRTUAL_PS1:-}"
|
||||
export PS1
|
||||
unset _OLD_VIRTUAL_PS1
|
||||
fi
|
||||
|
||||
unset VIRTUAL_ENV
|
||||
if [ ! "${1:-}" = "nondestructive" ] ; then
|
||||
# Self destruct!
|
||||
unset -f deactivate
|
||||
fi
|
||||
}
|
||||
|
||||
# unset irrelevant variables
|
||||
deactivate nondestructive
|
||||
|
||||
VIRTUAL_ENV="/home/untriex/Documents/Mabasej_Team/.venv"
|
||||
export VIRTUAL_ENV
|
||||
|
||||
_OLD_VIRTUAL_PATH="$PATH"
|
||||
PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||
export PATH
|
||||
|
||||
# unset PYTHONHOME if set
|
||||
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
|
||||
# could use `if (set -u; : $PYTHONHOME) ;` in bash
|
||||
if [ -n "${PYTHONHOME:-}" ] ; then
|
||||
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
|
||||
unset PYTHONHOME
|
||||
fi
|
||||
|
||||
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
|
||||
_OLD_VIRTUAL_PS1="${PS1:-}"
|
||||
PS1="(.venv) ${PS1:-}"
|
||||
export PS1
|
||||
fi
|
||||
|
||||
# This should detect bash and zsh, which have a hash command that must
|
||||
# be called to get it to forget past commands. Without forgetting
|
||||
# past commands the $PATH changes we made may not be respected
|
||||
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
|
||||
hash -r 2> /dev/null
|
||||
fi
|
@ -1,25 +0,0 @@
|
||||
# This file must be used with "source bin/activate.csh" *from csh*.
|
||||
# You cannot run it directly.
|
||||
# Created by Davide Di Blasi <davidedb@gmail.com>.
|
||||
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
|
||||
|
||||
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
|
||||
|
||||
# Unset irrelevant variables.
|
||||
deactivate nondestructive
|
||||
|
||||
setenv VIRTUAL_ENV "/home/untriex/Documents/Mabasej_Team/.venv"
|
||||
|
||||
set _OLD_VIRTUAL_PATH="$PATH"
|
||||
setenv PATH "$VIRTUAL_ENV/bin:$PATH"
|
||||
|
||||
|
||||
set _OLD_VIRTUAL_PROMPT="$prompt"
|
||||
|
||||
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
||||
set prompt = "(.venv) $prompt"
|
||||
endif
|
||||
|
||||
alias pydoc python -m pydoc
|
||||
|
||||
rehash
|
@ -1,64 +0,0 @@
|
||||
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
|
||||
# (https://fishshell.com/); you cannot run it directly.
|
||||
|
||||
function deactivate -d "Exit virtual environment and return to normal shell environment"
|
||||
# reset old environment variables
|
||||
if test -n "$_OLD_VIRTUAL_PATH"
|
||||
set -gx PATH $_OLD_VIRTUAL_PATH
|
||||
set -e _OLD_VIRTUAL_PATH
|
||||
end
|
||||
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
|
||||
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
|
||||
set -e _OLD_VIRTUAL_PYTHONHOME
|
||||
end
|
||||
|
||||
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
|
||||
functions -e fish_prompt
|
||||
set -e _OLD_FISH_PROMPT_OVERRIDE
|
||||
functions -c _old_fish_prompt fish_prompt
|
||||
functions -e _old_fish_prompt
|
||||
end
|
||||
|
||||
set -e VIRTUAL_ENV
|
||||
if test "$argv[1]" != "nondestructive"
|
||||
# Self-destruct!
|
||||
functions -e deactivate
|
||||
end
|
||||
end
|
||||
|
||||
# Unset irrelevant variables.
|
||||
deactivate nondestructive
|
||||
|
||||
set -gx VIRTUAL_ENV "/home/untriex/Documents/Mabasej_Team/.venv"
|
||||
|
||||
set -gx _OLD_VIRTUAL_PATH $PATH
|
||||
set -gx PATH "$VIRTUAL_ENV/bin" $PATH
|
||||
|
||||
# Unset PYTHONHOME if set.
|
||||
if set -q PYTHONHOME
|
||||
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
|
||||
set -e PYTHONHOME
|
||||
end
|
||||
|
||||
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
|
||||
# fish uses a function instead of an env var to generate the prompt.
|
||||
|
||||
# Save the current fish_prompt function as the function _old_fish_prompt.
|
||||
functions -c fish_prompt _old_fish_prompt
|
||||
|
||||
# With the original prompt function renamed, we can override with our own.
|
||||
function fish_prompt
|
||||
# Save the return status of the last command.
|
||||
set -l old_status $status
|
||||
|
||||
# Output the venv prompt; color taken from the blue of the Python logo.
|
||||
printf "%s%s%s" (set_color 4B8BBE) "(.venv) " (set_color normal)
|
||||
|
||||
# Restore the return status of the previous command.
|
||||
echo "exit $old_status" | .
|
||||
# Output the original/"old" prompt.
|
||||
_old_fish_prompt
|
||||
end
|
||||
|
||||
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
|
||||
end
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from ampy.cli import cli
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(cli())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from chardet.cli.chardetect import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from dotenv.cli import cli
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(cli())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from hypercorn.__main__ import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from serial.tools.miniterm import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1,8 +0,0 @@
|
||||
#!/home/untriex/Documents/Mabasej_Team/.venv/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
from serial.tools.list_ports import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
@ -1 +0,0 @@
|
||||
python3.9
|
@ -1 +0,0 @@
|
||||
python3.9
|
@ -1 +0,0 @@
|
||||
/usr/bin/python3.9
|
@ -1 +0,0 @@
|
||||
pip
|
@ -1,22 +0,0 @@
|
||||
Copyright P G Jones 2018.
|
||||
|
||||
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.
|
@ -1,159 +0,0 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: Hypercorn
|
||||
Version: 0.11.2
|
||||
Summary: A ASGI Server based on Hyper libraries and inspired by Gunicorn.
|
||||
Home-page: https://gitlab.com/pgjones/hypercorn/
|
||||
Author: P G Jones
|
||||
Author-email: philip.graham.jones@googlemail.com
|
||||
License: MIT
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 4 - Beta
|
||||
Classifier: Environment :: Web Environment
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Requires-Python: >=3.7
|
||||
Requires-Dist: h11
|
||||
Requires-Dist: h2 (>=3.1.0)
|
||||
Requires-Dist: priority
|
||||
Requires-Dist: toml
|
||||
Requires-Dist: wsproto (>=0.14.0)
|
||||
Requires-Dist: typing-extensions ; python_version < "3.8"
|
||||
Provides-Extra: h3
|
||||
Requires-Dist: aioquic (<1.0,>=0.9.0) ; extra == 'h3'
|
||||
Provides-Extra: tests
|
||||
Requires-Dist: hypothesis ; extra == 'tests'
|
||||
Requires-Dist: mock ; extra == 'tests'
|
||||
Requires-Dist: pytest ; extra == 'tests'
|
||||
Requires-Dist: pytest-asyncio ; extra == 'tests'
|
||||
Requires-Dist: pytest-cov ; extra == 'tests'
|
||||
Requires-Dist: pytest-trio ; extra == 'tests'
|
||||
Requires-Dist: trio ; extra == 'tests'
|
||||
Provides-Extra: trio
|
||||
Requires-Dist: trio (>=0.11.0) ; extra == 'trio'
|
||||
Provides-Extra: uvloop
|
||||
Requires-Dist: uvloop ; extra == 'uvloop'
|
||||
|
||||
Hypercorn
|
||||
=========
|
||||
|
||||
.. image:: https://assets.gitlab-static.net/pgjones/hypercorn/raw/master/artwork/logo.png
|
||||
:alt: Hypercorn logo
|
||||
|
||||
|Build Status| |docs| |pypi| |http| |python| |license|
|
||||
|
||||
Hypercorn is an `ASGI
|
||||
<https://github.com/django/asgiref/blob/master/specs/asgi.rst>`_ web
|
||||
server based on the sans-io hyper, `h11
|
||||
<https://github.com/python-hyper/h11>`_, `h2
|
||||
<https://github.com/python-hyper/hyper-h2>`_, and `wsproto
|
||||
<https://github.com/python-hyper/wsproto>`_ libraries and inspired by
|
||||
Gunicorn. Hypercorn supports HTTP/1, HTTP/2, WebSockets (over HTTP/1
|
||||
and HTTP/2), ASGI/2, and ASGI/3 specifications. Hypercorn can utilise
|
||||
asyncio, uvloop, or trio worker types.
|
||||
|
||||
Hypercorn can optionally serve the current draft of the HTTP/3
|
||||
specification using the `aioquic
|
||||
<https://github.com/aiortc/aioquic/>`_ library. To enable this install
|
||||
the ``h3`` optional extra, ``pip install hypercorn[h3]`` and then
|
||||
choose a quic binding e.g. ``hypercorn --quic-bind localhost:4433
|
||||
...``.
|
||||
|
||||
Hypercorn was initially part of `Quart
|
||||
<https://gitlab.com/pgjones/quart>`_ before being separated out into a
|
||||
standalone ASGI server. Hypercorn forked from version 0.5.0 of Quart.
|
||||
|
||||
Quickstart
|
||||
----------
|
||||
|
||||
Hypercorn can be installed via `pip
|
||||
<https://docs.python.org/3/installing/index.html>`_,
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ pip install hypercorn
|
||||
|
||||
and requires Python 3.7.0 or higher.
|
||||
|
||||
With hypercorn installed ASGI frameworks (or apps) can be served via
|
||||
Hypercorn via the command line,
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ hypercorn module:app
|
||||
|
||||
Alternatively Hypercorn can be used programatically,
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import asyncio
|
||||
from hypercorn.config import Config
|
||||
from hypercorn.asyncio import serve
|
||||
|
||||
from module import app
|
||||
|
||||
asyncio.run(serve(app, Config()))
|
||||
|
||||
learn more (including a Trio example of the above) in the `API usage
|
||||
<https://pgjones.gitlab.io/hypercorn/how_to_guides/api_usage.html>`_
|
||||
docs.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Hypercorn is developed on `GitLab
|
||||
<https://gitlab.com/pgjones/hypercorn>`_. If you come across an issue,
|
||||
or have a feature request please open an `issue
|
||||
<https://gitlab.com/pgjones/hypercorn/issues>`_. If you want to
|
||||
contribute a fix or the feature-implementation please do (typo fixes
|
||||
welcome), by proposing a `merge request
|
||||
<https://gitlab.com/pgjones/hypercorn/merge_requests>`_.
|
||||
|
||||
Testing
|
||||
~~~~~~~
|
||||
|
||||
The best way to test Hypercorn is with `Tox
|
||||
<https://tox.readthedocs.io>`_,
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ pipenv install tox
|
||||
$ tox
|
||||
|
||||
this will check the code style and run the tests.
|
||||
|
||||
Help
|
||||
----
|
||||
|
||||
The Hypercorn `documentation <https://pgjones.gitlab.io/hypercorn/>`_
|
||||
is the best place to start, after that try searching stack overflow,
|
||||
if you still can't find an answer please `open an issue
|
||||
<https://gitlab.com/pgjones/hypercorn/issues>`_.
|
||||
|
||||
|
||||
.. |Build Status| image:: https://gitlab.com/pgjones/hypercorn/badges/master/pipeline.svg
|
||||
:target: https://gitlab.com/pgjones/hypercorn/commits/master
|
||||
|
||||
.. |docs| image:: https://img.shields.io/badge/docs-passing-brightgreen.svg
|
||||
:target: https://pgjones.gitlab.io/hypercorn/
|
||||
|
||||
.. |pypi| image:: https://img.shields.io/pypi/v/hypercorn.svg
|
||||
:target: https://pypi.python.org/pypi/Hypercorn/
|
||||
|
||||
.. |http| image:: https://img.shields.io/badge/http-1.0,1.1,2-orange.svg
|
||||
:target: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
|
||||
|
||||
.. |python| image:: https://img.shields.io/pypi/pyversions/hypercorn.svg
|
||||
:target: https://pypi.python.org/pypi/Hypercorn/
|
||||
|
||||
.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg
|
||||
:target: https://gitlab.com/pgjones/hypercorn/blob/master/LICENSE
|
||||
|
||||
|
@ -1,84 +0,0 @@
|
||||
../../../bin/hypercorn,sha256=oOEgM4z3zmD0l9nolNOYsTXSJX4IAFqQw5isLyFE_Tk,254
|
||||
Hypercorn-0.11.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
Hypercorn-0.11.2.dist-info/LICENSE,sha256=HjGdhzPYNEZ3zQ7mwqjMBgHHRId5HViyayt-8GMMK38,1050
|
||||
Hypercorn-0.11.2.dist-info/METADATA,sha256=_YgWC-LPDlyhr8xY6Cjkd7wrlgSS5K4InaeuEhKzqhI,5216
|
||||
Hypercorn-0.11.2.dist-info/RECORD,,
|
||||
Hypercorn-0.11.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
Hypercorn-0.11.2.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
|
||||
Hypercorn-0.11.2.dist-info/entry_points.txt,sha256=HV9e4tNKTeIJbe1PIswRWGn4jbCUQqfIbcAIV68Znuk,55
|
||||
Hypercorn-0.11.2.dist-info/top_level.txt,sha256=zSgQlh13xK80SFqsUPaG5-83qTJOzqYTBfP9XFcvB_Y,10
|
||||
hypercorn/__about__.py,sha256=bmMNWd6X6fx5JJd3CqzukH9Aez4xKCZuJNcmMU1pbEc,23
|
||||
hypercorn/__init__.py,sha256=ZBbFBwpZeEyk7_9xleLlt7KqM48wYv7kjY2we02gsqs,99
|
||||
hypercorn/__main__.py,sha256=W9ES4hoULQqPYUKUP_mMJWRzs_Zb3uQZpD30lWZmczk,9596
|
||||
hypercorn/__pycache__/__about__.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/__init__.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/__main__.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/config.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/events.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/logging.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/run.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/statsd.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/typing.cpython-39.pyc,,
|
||||
hypercorn/__pycache__/utils.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__init__.py,sha256=eq15FULu-0bJqMSMakcm0vxWz-m31NaKzJtCviZtKJI,1201
|
||||
hypercorn/asyncio/__pycache__/__init__.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/context.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/lifespan.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/run.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/statsd.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/task_group.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/tcp_server.cpython-39.pyc,,
|
||||
hypercorn/asyncio/__pycache__/udp_server.cpython-39.pyc,,
|
||||
hypercorn/asyncio/context.py,sha256=GXFl5OHbsAIjERdjlvShs25jYG3_1EPXzVcyMas0ZEk,1919
|
||||
hypercorn/asyncio/lifespan.py,sha256=cGj4Z85ll7jUSx0AaxBpV1SrvbMSKpj5O63NtTkkyRo,3231
|
||||
hypercorn/asyncio/run.py,sha256=nrE8lECEUpxbg8Jrx9ozKKuyk37YsDsGZRsMQgDYZTU,8319
|
||||
hypercorn/asyncio/statsd.py,sha256=0AhRzPxD2M2cWl-E8MVPeB2rMFgEV684InIE9F0zUy4,733
|
||||
hypercorn/asyncio/task_group.py,sha256=HFvF7u_Nsf4k8I63KbnIi6JlnrVZNvNysT6bbTvnpyQ,927
|
||||
hypercorn/asyncio/tcp_server.py,sha256=SuOqCbKExDzJ8AMvtt67bohDidT52F2S1_urbCTQbls,4982
|
||||
hypercorn/asyncio/udp_server.py,sha256=eQBFVy-j-Gu9hGgzvflWSCAdJdoni5Y50stWyC44bUw,2120
|
||||
hypercorn/config.py,sha256=Ol6c5b93IKTqJxtxGY7hBt2ed4m7U0xzdarY_7aTLEM,12753
|
||||
hypercorn/events.py,sha256=bEitGLlNzRngMXAWw22nhw7PhhZCRaU9T9BdKNlpzoM,440
|
||||
hypercorn/logging.py,sha256=XeLerzMiLqV0gWL6bF0pAEKDKFLEJ5tL0n50VE9QQ_g,6666
|
||||
hypercorn/middleware/__init__.py,sha256=H2RPiJynxovfC6szNHzbZg5ec_C2IChYsft5blPRNNg,297
|
||||
hypercorn/middleware/__pycache__/__init__.cpython-39.pyc,,
|
||||
hypercorn/middleware/__pycache__/dispatcher.cpython-39.pyc,,
|
||||
hypercorn/middleware/__pycache__/http_to_https.cpython-39.pyc,,
|
||||
hypercorn/middleware/__pycache__/wsgi.cpython-39.pyc,,
|
||||
hypercorn/middleware/dispatcher.py,sha256=K-FJiMixBYyP93HjqV1n59rG0-kpF-ORsHQlskeA__0,4362
|
||||
hypercorn/middleware/http_to_https.py,sha256=I3bTSv0DKgZIMrq_QCHTq9tmIaMWYbdHUrHcQAjXPrQ,2628
|
||||
hypercorn/middleware/wsgi.py,sha256=_yM3QY-lakZcgDbn_webKyi32B2HhJ9CNxP1O5WBRB8,4885
|
||||
hypercorn/protocol/__init__.py,sha256=BBGsnx1I6qPHQ-ZYkNz1fpHS5RT3PVsFxxA_9Cvioxo,2612
|
||||
hypercorn/protocol/__pycache__/__init__.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/events.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/h11.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/h2.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/h3.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/http_stream.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/quic.cpython-39.pyc,,
|
||||
hypercorn/protocol/__pycache__/ws_stream.cpython-39.pyc,,
|
||||
hypercorn/protocol/events.py,sha256=z4ujv2Xg085YNpbE36Hy6qDfSOPmi6rb8QfPpWEh2xw,675
|
||||
hypercorn/protocol/h11.py,sha256=MsMrWJHv-Wv8-s9Rz2cdDf9wyWm0oqvvM0bN5ES_R0E,10593
|
||||
hypercorn/protocol/h2.py,sha256=K3WYXYbHY3u19KsDi8vW7H0wzszKU0X-GHG9MKbmheE,13817
|
||||
hypercorn/protocol/h3.py,sha256=Zn9Apxdkxjz_7mQWsM7M-u6_gVGqahfdVBkI5oClPfk,4954
|
||||
hypercorn/protocol/http_stream.py,sha256=bBs1V_D3avhhFqz1IillgMa021DnEleprzIUn2IaOsU,6967
|
||||
hypercorn/protocol/quic.py,sha256=qSHgGL4QBjz-TaJ5NNMNm3ZSOCl3fWtO9UjuRpBpIMo,4758
|
||||
hypercorn/protocol/ws_stream.py,sha256=GQWz5NVzPICdup5b5-B3yktpFtzWpZcxTCUqYmu8z84,14020
|
||||
hypercorn/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
|
||||
hypercorn/run.py,sha256=PUnAfyM_zw_rFNEWmnQDM1IIG_H9K4uwAheIvJTgefo,2247
|
||||
hypercorn/statsd.py,sha256=viEyWGm1fOYB6KvU6kmNftV0wR8uBrBa-u7UECvzQeI,3784
|
||||
hypercorn/trio/__init__.py,sha256=P7v1a9OHcoKK5EnfsMOHuS9LdTEGht3hPgteGiQ8N5M,1309
|
||||
hypercorn/trio/__pycache__/__init__.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/context.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/lifespan.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/run.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/statsd.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/tcp_server.cpython-39.pyc,,
|
||||
hypercorn/trio/__pycache__/udp_server.cpython-39.pyc,,
|
||||
hypercorn/trio/context.py,sha256=2-qUGgQLh7JS_Mlk2TyMEbr_MgPMcz_Sd3IOt9Hy_8o,2236
|
||||
hypercorn/trio/lifespan.py,sha256=XdE-xVP8ZMAfY9YQ0sHZ7AAuHvUnSnvjq_3wuGK5p7k,2896
|
||||
hypercorn/trio/run.py,sha256=X5IE0diyHjeZ9lw9DUx7xZq7cpgj8dRGtyCeYxf4Oxo,4348
|
||||
hypercorn/trio/statsd.py,sha256=ilyrPPK49PcQJjs6tAfd1AtQvZd6kfP-q70N3waqrPo,450
|
||||
hypercorn/trio/tcp_server.py,sha256=oSZdBp0Y54t1m0StYy37xAHa3UHIiGegtiwnMK6VwCg,5145
|
||||
hypercorn/trio/udp_server.py,sha256=yrzPRYhaPGOT9tt406_m1Gq02QuW4bTbaI5cD28LuaA,1306
|
||||
hypercorn/typing.py,sha256=9F9ApOXAeXhlkJO_QNKk_gsp6vgOR3g4iCtdpmymCX4,6737
|
||||
hypercorn/utils.py,sha256=sgTGJV4qHy3zNEa2W-UySRFqPWlf5ViEGCG5lDM1TuQ,7558
|
@ -1,5 +0,0 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.36.2)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
@ -1,3 +0,0 @@
|
||||
[console_scripts]
|
||||
hypercorn = hypercorn.__main__:main
|
||||
|
@ -1 +0,0 @@
|
||||
hypercorn
|
Binary file not shown.
Binary file not shown.
@ -1,123 +0,0 @@
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import importlib
|
||||
import warnings
|
||||
|
||||
|
||||
is_pypy = '__pypy__' in sys.builtin_module_names
|
||||
|
||||
|
||||
def warn_distutils_present():
|
||||
if 'distutils' not in sys.modules:
|
||||
return
|
||||
if is_pypy and sys.version_info < (3, 7):
|
||||
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
|
||||
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
|
||||
return
|
||||
warnings.warn(
|
||||
"Distutils was imported before Setuptools, but importing Setuptools "
|
||||
"also replaces the `distutils` module in `sys.modules`. This may lead "
|
||||
"to undesirable behaviors or errors. To avoid these issues, avoid "
|
||||
"using distutils directly, ensure that setuptools is installed in the "
|
||||
"traditional way (e.g. not an editable install), and/or make sure "
|
||||
"that setuptools is always imported before distutils.")
|
||||
|
||||
|
||||
def clear_distutils():
|
||||
if 'distutils' not in sys.modules:
|
||||
return
|
||||
warnings.warn("Setuptools is replacing distutils.")
|
||||
mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
|
||||
for name in mods:
|
||||
del sys.modules[name]
|
||||
|
||||
|
||||
def enabled():
|
||||
"""
|
||||
Allow selection of distutils by environment variable.
|
||||
"""
|
||||
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
|
||||
return which == 'local'
|
||||
|
||||
|
||||
def ensure_local_distutils():
|
||||
clear_distutils()
|
||||
distutils = importlib.import_module('setuptools._distutils')
|
||||
distutils.__name__ = 'distutils'
|
||||
sys.modules['distutils'] = distutils
|
||||
|
||||
# sanity check that submodules load as expected
|
||||
core = importlib.import_module('distutils.core')
|
||||
assert '_distutils' in core.__file__, core.__file__
|
||||
|
||||
|
||||
def do_override():
|
||||
"""
|
||||
Ensure that the local copy of distutils is preferred over stdlib.
|
||||
|
||||
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
|
||||
for more motivation.
|
||||
"""
|
||||
if enabled():
|
||||
warn_distutils_present()
|
||||
ensure_local_distutils()
|
||||
|
||||
|
||||
class DistutilsMetaFinder:
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if path is not None:
|
||||
return
|
||||
|
||||
method_name = 'spec_for_{fullname}'.format(**locals())
|
||||
method = getattr(self, method_name, lambda: None)
|
||||
return method()
|
||||
|
||||
def spec_for_distutils(self):
|
||||
import importlib.abc
|
||||
import importlib.util
|
||||
|
||||
class DistutilsLoader(importlib.abc.Loader):
|
||||
|
||||
def create_module(self, spec):
|
||||
return importlib.import_module('setuptools._distutils')
|
||||
|
||||
def exec_module(self, module):
|
||||
pass
|
||||
|
||||
return importlib.util.spec_from_loader('distutils', DistutilsLoader())
|
||||
|
||||
def spec_for_pip(self):
|
||||
"""
|
||||
Ensure stdlib distutils when running under pip.
|
||||
See pypa/pip#8761 for rationale.
|
||||
"""
|
||||
if self.pip_imported_during_build():
|
||||
return
|
||||
clear_distutils()
|
||||
self.spec_for_distutils = lambda: None
|
||||
|
||||
@staticmethod
|
||||
def pip_imported_during_build():
|
||||
"""
|
||||
Detect if pip is being imported in a build script. Ref #2355.
|
||||
"""
|
||||
import traceback
|
||||
return any(
|
||||
frame.f_globals['__file__'].endswith('setup.py')
|
||||
for frame, line in traceback.walk_stack(None)
|
||||
)
|
||||
|
||||
|
||||
DISTUTILS_FINDER = DistutilsMetaFinder()
|
||||
|
||||
|
||||
def add_shim():
|
||||
sys.meta_path.insert(0, DISTUTILS_FINDER)
|
||||
|
||||
|
||||
def remove_shim():
|
||||
try:
|
||||
sys.meta_path.remove(DISTUTILS_FINDER)
|
||||
except ValueError:
|
||||
pass
|
Binary file not shown.
Binary file not shown.
@ -1 +0,0 @@
|
||||
__import__('_distutils_hack').do_override()
|
@ -1 +0,0 @@
|
||||
pip
|
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2016 Adafruit Industries
|
||||
|
||||
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.
|
@ -1,147 +0,0 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: adafruit-ampy
|
||||
Version: 1.0.7
|
||||
Summary: ampy (Adafruit MicroPython tool) is a command line tool to interact with a CircuitPython or MicroPython board over a serial connection.
|
||||
Home-page: https://github.com/adafruit/ampy
|
||||
Author: Adafruit Industries
|
||||
Author-email: circuitpython@adafruit.com
|
||||
License: MIT
|
||||
Keywords: adafruit ampy hardware micropython circuitpython
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 4 - Beta
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 2.6
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.3
|
||||
Classifier: Programming Language :: Python :: 3.4
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Description-Content-Type: text/markdown
|
||||
Requires-Dist: click
|
||||
Requires-Dist: pyserial
|
||||
Requires-Dist: python-dotenv
|
||||
|
||||
# ampy
|
||||
Adafruit MicroPython Tool (ampy) - Utility to interact with a CircuitPython or MicroPython board over a serial connection.
|
||||
|
||||
Ampy is meant to be a simple command line tool to manipulate files and run code on a CircuitPython or
|
||||
MicroPython board over its serial connection.
|
||||
With ampy you can send files from your computer to the
|
||||
board's file system, download files from a board to your computer, and even send a Python script
|
||||
to a board to be executed.
|
||||
|
||||
Note that ampy by design is meant to be simple and does not support advanced interaction like a shell
|
||||
or terminal to send input to a board. Check out other MicroPython tools
|
||||
like [rshell](https://github.com/dhylands/rshell)
|
||||
or [mpfshell](https://github.com/wendlers/mpfshell) for more advanced interaction with boards.
|
||||
|
||||
## Installation
|
||||
|
||||
You can use ampy with either Python 2.7.x or 3.x and can install it easily from
|
||||
Python's package index. On MacOS or Linux, in a terminal run the following command (assuming
|
||||
Python 3):
|
||||
|
||||
pip3 install --user adafruit-ampy
|
||||
|
||||
On Windows, do:
|
||||
|
||||
pip install adafruit-ampy
|
||||
|
||||
Note on some Linux and Mac OSX systems you might need to run as root with sudo:
|
||||
|
||||
sudo pip3 install adafruit-ampy
|
||||
|
||||
If you don't have Python 3 then try using Python 2 with:
|
||||
|
||||
pip install adafruit-ampy
|
||||
|
||||
Once installed verify you can run the ampy program and get help output:
|
||||
|
||||
ampy --help
|
||||
|
||||
You should see usage information displayed like below:
|
||||
|
||||
Usage: ampy [OPTIONS] COMMAND [ARGS]...
|
||||
|
||||
ampy - Adafruit MicroPython Tool
|
||||
|
||||
Ampy is a tool to control MicroPython boards over a serial connection.
|
||||
Using ampy you can manipulate files on the board's internal filesystem and
|
||||
even run scripts.
|
||||
|
||||
Options:
|
||||
-p, --port PORT Name of serial port for connected board. [required]
|
||||
-b, --baud BAUD Baud rate for the serial connection. (default 115200)
|
||||
--help Show this message and exit.
|
||||
|
||||
Commands:
|
||||
get Retrieve a file from the board.
|
||||
ls List contents of a directory on the board.
|
||||
put Put a file on the board.
|
||||
rm Remove a file from the board.
|
||||
run Run a script and print its output.
|
||||
|
||||
If you'd like to install from the Github source then use the standard Python
|
||||
setup.py install (or develop mode):
|
||||
|
||||
python3 setup.py install
|
||||
|
||||
Note to run the unit tests on Python 2 you must install the mock library:
|
||||
|
||||
pip install mock
|
||||
|
||||
## Usage
|
||||
|
||||
Ampy is made to talk to a CircuitPython MicroPython board over its serial connection. You will
|
||||
need your board connected and any drivers to access it serial port installed.
|
||||
Then for example to list the files on the board run a command like:
|
||||
|
||||
ampy --port /dev/tty.SLAB_USBtoUART ls
|
||||
|
||||
You should see a list of files on the board's root directory printed to the
|
||||
terminal. Note that you'll need to change the port parameter to the name or path
|
||||
to the serial port that the MicroPython board is connected to.
|
||||
|
||||
Other commands are available, run ampy with --help to see more information:
|
||||
|
||||
ampy --help
|
||||
|
||||
Each subcommand has its own help, for example to see help for the ls command run (note you
|
||||
unfortunately must have a board connected and serial port specified):
|
||||
|
||||
ampy --port /dev/tty.SLAB_USBtoUART ls --help
|
||||
|
||||
## Configuration
|
||||
|
||||
For convenience you can set an `AMPY_PORT` environment variable which will be used
|
||||
if the port parameter is not specified. For example on Linux or OSX:
|
||||
|
||||
export AMPY_PORT=/dev/tty.SLAB_USBtoUART
|
||||
ampy ls
|
||||
|
||||
Or on Windows (untested) try the SET command:
|
||||
|
||||
set AMPY_PORT=COM4
|
||||
ampy ls
|
||||
|
||||
Similarly, you can set `AMPY_BAUD` and `AMPY_DELAY` to control your baud rate and
|
||||
the delay before entering RAW MODE.
|
||||
|
||||
To set these variables automatically each time you run `ampy`, copy them into a
|
||||
file named `.ampy`:
|
||||
|
||||
```sh
|
||||
# Example .ampy file
|
||||
# Please fill in your own port, baud rate, and delay
|
||||
AMPY_PORT=/dev/cu.wchusbserial1410
|
||||
AMPY_BAUD=115200
|
||||
# Fix for macOS users' "Could not enter raw repl"; try 2.0 and lower from there:
|
||||
AMPY_DELAY=0.5
|
||||
```
|
||||
|
||||
You can put the `.ampy` file in your working directory, one of its parents, or in
|
||||
your home directory.
|
||||
|
||||
|
@ -1,17 +0,0 @@
|
||||
../../../bin/ampy,sha256=seXbLemZP9C8J-krbRe7esl9AmznESl6DPbxmU0Fzhk,242
|
||||
adafruit_ampy-1.0.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
adafruit_ampy-1.0.7.dist-info/LICENSE,sha256=9gQ2ZE4GYwHUwujx8GdKFXsfYOT9VYZxe5nd4lXMGM0,1076
|
||||
adafruit_ampy-1.0.7.dist-info/METADATA,sha256=J30k_3TI3-vG8GSll8IWg3yBpCFMuCIr0tvNswYxTf0,5087
|
||||
adafruit_ampy-1.0.7.dist-info/RECORD,,
|
||||
adafruit_ampy-1.0.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
adafruit_ampy-1.0.7.dist-info/WHEEL,sha256=CihQvCnsGZQBGAHLEUMf0IdA4fRduS_NBUTMgCTtvPM,110
|
||||
adafruit_ampy-1.0.7.dist-info/entry_points.txt,sha256=zTIIUmlgcc2fs6jESYBEpIg6vF6O0rHJrTPpe0FVhdM,39
|
||||
adafruit_ampy-1.0.7.dist-info/top_level.txt,sha256=V20_LZHKhLbhLQGa8h22OpV1VD6ngxxFNEukjkCBn2c,5
|
||||
ampy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ampy/__pycache__/__init__.cpython-39.pyc,,
|
||||
ampy/__pycache__/cli.cpython-39.pyc,,
|
||||
ampy/__pycache__/files.cpython-39.pyc,,
|
||||
ampy/__pycache__/pyboard.cpython-39.pyc,,
|
||||
ampy/cli.py,sha256=SVOtiASrbDeanLyU86kKSwqZ1gPX_-P4w6eOh3TJW_8,14955
|
||||
ampy/files.py,sha256=swfqotremCZLeuT_sGqRdJXowB-PHvBou_Ic6JtUn3o,13160
|
||||
ampy/pyboard.py,sha256=JmwUfwKMKgnWzn-CNOtb-v0ZQJM5YyHaZHlVebQnBHY,11914
|
@ -1,6 +0,0 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.32.2)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py2-none-any
|
||||
Tag: py3-none-any
|
||||
|
@ -1,3 +0,0 @@
|
||||
[console_scripts]
|
||||
ampy = ampy.cli:cli
|
||||
|
@ -1 +0,0 @@
|
||||
ampy
|
@ -1 +0,0 @@
|
||||
pip
|
@ -1,202 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
@ -1,180 +0,0 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: aiofiles
|
||||
Version: 0.6.0
|
||||
Summary: File support for asyncio.
|
||||
Home-page: https://github.com/Tinche/aiofiles
|
||||
Author: Tin Tvrtkovic
|
||||
Author-email: tinchester@gmail.com
|
||||
License: Apache 2.0
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 4 - Beta
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: Apache Software License
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Topic :: System :: Filesystems
|
||||
|
||||
aiofiles: file support for asyncio
|
||||
==================================
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/aiofiles.svg
|
||||
:target: https://pypi.python.org/pypi/aiofiles
|
||||
|
||||
.. image:: https://travis-ci.org/Tinche/aiofiles.svg?branch=master
|
||||
:target: https://travis-ci.org/Tinche/aiofiles
|
||||
|
||||
.. image:: https://codecov.io/gh/Tinche/aiofiles/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/Tinche/aiofiles
|
||||
|
||||
.. image:: https://img.shields.io/pypi/pyversions/aiofiles.svg
|
||||
:target: https://github.com/Tinche/aiofiles
|
||||
:alt: Supported Python versions
|
||||
|
||||
**aiofiles** is an Apache2 licensed library, written in Python, for handling local
|
||||
disk files in asyncio applications.
|
||||
|
||||
Ordinary local file IO is blocking, and cannot easily and portably made
|
||||
asynchronous. This means doing file IO may interfere with asyncio applications,
|
||||
which shouldn't block the executing thread. aiofiles helps with this by
|
||||
introducing asynchronous versions of files that support delegating operations to
|
||||
a separate thread pool.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async with aiofiles.open('filename', mode='r') as f:
|
||||
contents = await f.read()
|
||||
print(contents)
|
||||
'My file contents'
|
||||
|
||||
Asynchronous iteration is also supported.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async with aiofiles.open('filename') as f:
|
||||
async for line in f:
|
||||
...
|
||||
|
||||
Features
|
||||
--------
|
||||
|
||||
- a file API very similar to Python's standard, blocking API
|
||||
- support for buffered and unbuffered binary files, and buffered text files
|
||||
- support for ``async``/``await`` (:PEP:`492`) constructs
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
To install aiofiles, simply:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ pip install aiofiles
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Files are opened using the ``aiofiles.open()`` coroutine, which in addition to
|
||||
mirroring the builtin ``open`` accepts optional ``loop`` and ``executor``
|
||||
arguments. If ``loop`` is absent, the default loop will be used, as per the
|
||||
set asyncio policy. If ``executor`` is not specified, the default event loop
|
||||
executor will be used.
|
||||
|
||||
In case of success, an asynchronous file object is returned with an
|
||||
API identical to an ordinary file, except the following methods are coroutines
|
||||
and delegate to an executor:
|
||||
|
||||
* ``close``
|
||||
* ``flush``
|
||||
* ``isatty``
|
||||
* ``read``
|
||||
* ``readall``
|
||||
* ``read1``
|
||||
* ``readinto``
|
||||
* ``readline``
|
||||
* ``readlines``
|
||||
* ``seek``
|
||||
* ``seekable``
|
||||
* ``tell``
|
||||
* ``truncate``
|
||||
* ``writable``
|
||||
* ``write``
|
||||
* ``writelines``
|
||||
|
||||
In case of failure, one of the usual exceptions will be raised.
|
||||
|
||||
The ``aiofiles.os`` module contains executor-enabled coroutine versions of
|
||||
several useful ``os`` functions that deal with files:
|
||||
|
||||
* ``stat``
|
||||
* ``sendfile``
|
||||
* ``rename``
|
||||
* ``remove``
|
||||
* ``mkdir``
|
||||
* ``rmdir``
|
||||
|
||||
Writing tests for aiofiles
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Real file IO can be mocked by patching ``aiofiles.threadpool.sync_open``
|
||||
as desired. The return type also needs to be registered with the
|
||||
``aiofiles.threadpool.wrap`` dispatcher:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
aiofiles.threadpool.wrap.register(mock.MagicMock)(
|
||||
lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs))
|
||||
|
||||
async def test_stuff():
|
||||
data = 'data'
|
||||
mock_file = mock.MagicMock()
|
||||
|
||||
with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open:
|
||||
async with aiofiles.open('filename', 'w') as f:
|
||||
await f.write(data)
|
||||
|
||||
mock_file.write.assert_called_once_with(data)
|
||||
|
||||
History
|
||||
~~~~~~~
|
||||
|
||||
0.6.0 (2020-10-27)
|
||||
``````````````````
|
||||
- `aiofiles` is now tested on ppc64le.
|
||||
- Added `name` and `mode` properties to async file objects.
|
||||
`#82 <https://github.com/Tinche/aiofiles/pull/82>`_
|
||||
- Fixed a DeprecationWarning internally.
|
||||
`#75 <https://github.com/Tinche/aiofiles/pull/75>`_
|
||||
- Python 3.9 support and tests.
|
||||
|
||||
0.5.0 (2020-04-12)
|
||||
``````````````````
|
||||
- Python 3.8 support. Code base modernization (using ``async/await`` instead of ``asyncio.coroutine``/``yield from``).
|
||||
- Added ``aiofiles.os.remove``, ``aiofiles.os.rename``, ``aiofiles.os.mkdir``, ``aiofiles.os.rmdir``.
|
||||
`#62 <https://github.com/Tinche/aiofiles/pull/62>`_
|
||||
|
||||
|
||||
0.4.0 (2018-08-11)
|
||||
``````````````````
|
||||
- Python 3.7 support.
|
||||
- Removed Python 3.3/3.4 support. If you use these versions, stick to aiofiles 0.3.x.
|
||||
|
||||
0.3.2 (2017-09-23)
|
||||
``````````````````
|
||||
- The LICENSE is now included in the sdist.
|
||||
`#31 <https://github.com/Tinche/aiofiles/pull/31>`_
|
||||
|
||||
0.3.1 (2017-03-10)
|
||||
``````````````````
|
||||
|
||||
- Introduced a changelog.
|
||||
- ``aiofiles.os.sendfile`` will now work if the standard ``os`` module contains a ``sendfile`` function.
|
||||
|
||||
Contributing
|
||||
~~~~~~~~~~~~
|
||||
Contributions are very welcome. Tests can be run with ``tox``, please ensure
|
||||
the coverage at least stays the same before you submit a pull request.
|
||||
|
||||
|
@ -1,23 +0,0 @@
|
||||
aiofiles-0.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
aiofiles-0.6.0.dist-info/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
|
||||
aiofiles-0.6.0.dist-info/METADATA,sha256=yboBpvjtiTwhAL1GXInywZjtOYNEXBQQPWk-PdEYdtg,5335
|
||||
aiofiles-0.6.0.dist-info/RECORD,,
|
||||
aiofiles-0.6.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
aiofiles-0.6.0.dist-info/WHEEL,sha256=EVRjI69F5qVjm_YgqcTXPnTAv3BfSUr0WVAHuSP3Xoo,92
|
||||
aiofiles-0.6.0.dist-info/top_level.txt,sha256=sskrEAT1Ocyj9qsJIoeIQNAijBFwY2L0nqayXghOSI0,9
|
||||
aiofiles/__init__.py,sha256=iwkL4Mn8RhNjpPi8NzULHMocPHPlezoTDEOKJjKlF6A,124
|
||||
aiofiles/__pycache__/__init__.cpython-39.pyc,,
|
||||
aiofiles/__pycache__/_compat.cpython-39.pyc,,
|
||||
aiofiles/__pycache__/base.cpython-39.pyc,,
|
||||
aiofiles/__pycache__/os.cpython-39.pyc,,
|
||||
aiofiles/_compat.py,sha256=dk34urK9pKm1iqKNp2jKDWatAbn3Tt18eRn31G9BcAI,205
|
||||
aiofiles/base.py,sha256=RPOquSOYX2CADuni_xxPibzEbwxKUfxQRczGOw7E-sY,2021
|
||||
aiofiles/os.py,sha256=4WY_rJJcrdp4zDXmaKesitnCZGVJTjvF9Mv9fnJouoM,599
|
||||
aiofiles/threadpool/__init__.py,sha256=JaRiXZRaVvx32RvrUXwgZxAByrzqdmDcxi6t_P2iP6w,2273
|
||||
aiofiles/threadpool/__pycache__/__init__.cpython-39.pyc,,
|
||||
aiofiles/threadpool/__pycache__/binary.cpython-39.pyc,,
|
||||
aiofiles/threadpool/__pycache__/text.cpython-39.pyc,,
|
||||
aiofiles/threadpool/__pycache__/utils.cpython-39.pyc,,
|
||||
aiofiles/threadpool/binary.py,sha256=tRdJnH6ragF5Kr13oIBPJrljgTl3hWSOaHSXfHESRBk,1167
|
||||
aiofiles/threadpool/text.py,sha256=oVzmEh_sacMw3Gv4JjTpJG5ssC9vuwkILQVF1W--jc4,636
|
||||
aiofiles/threadpool/utils.py,sha256=FwRAqxqszQCo3UGAh3WJH8ts5zRDnDKvsgxOJ_-rti4,1244
|
@ -1,5 +0,0 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.35.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
@ -1 +0,0 @@
|
||||
aiofiles
|
@ -1,6 +0,0 @@
|
||||
"""Utilities for asyncio-friendly file handling."""
|
||||
from .threadpool import open
|
||||
|
||||
__version__ = "0.6.0"
|
||||
|
||||
__all__ = ["open"]
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,8 +0,0 @@
|
||||
import sys
|
||||
|
||||
try:
|
||||
from functools import singledispatch
|
||||
except ImportError: # pragma: nocover
|
||||
from singledispatch import singledispatch
|
||||
|
||||
PY_35 = sys.version_info >= (3, 5)
|
@ -1,88 +0,0 @@
|
||||
"""Various base classes."""
|
||||
from types import coroutine
|
||||
from collections.abc import Coroutine
|
||||
|
||||
|
||||
class AsyncBase:
|
||||
def __init__(self, file, loop, executor):
|
||||
self._file = file
|
||||
self._loop = loop
|
||||
self._executor = executor
|
||||
|
||||
def __aiter__(self):
|
||||
"""We are our own iterator."""
|
||||
return self
|
||||
|
||||
async def __anext__(self):
|
||||
"""Simulate normal file iteration."""
|
||||
line = await self.readline()
|
||||
if line:
|
||||
return line
|
||||
else:
|
||||
raise StopAsyncIteration
|
||||
|
||||
|
||||
class _ContextManager(Coroutine):
|
||||
__slots__ = ("_coro", "_obj")
|
||||
|
||||
def __init__(self, coro):
|
||||
self._coro = coro
|
||||
self._obj = None
|
||||
|
||||
def send(self, value):
|
||||
return self._coro.send(value)
|
||||
|
||||
def throw(self, typ, val=None, tb=None):
|
||||
if val is None:
|
||||
return self._coro.throw(typ)
|
||||
elif tb is None:
|
||||
return self._coro.throw(typ, val)
|
||||
else:
|
||||
return self._coro.throw(typ, val, tb)
|
||||
|
||||
def close(self):
|
||||
return self._coro.close()
|
||||
|
||||
@property
|
||||
def gi_frame(self):
|
||||
return self._coro.gi_frame
|
||||
|
||||
@property
|
||||
def gi_running(self):
|
||||
return self._coro.gi_running
|
||||
|
||||
@property
|
||||
def gi_code(self):
|
||||
return self._coro.gi_code
|
||||
|
||||
def __next__(self):
|
||||
return self.send(None)
|
||||
|
||||
@coroutine
|
||||
def __iter__(self):
|
||||
resp = yield from self._coro
|
||||
return resp
|
||||
|
||||
def __await__(self):
|
||||
resp = yield from self._coro
|
||||
return resp
|
||||
|
||||
async def __anext__(self):
|
||||
resp = await self._coro
|
||||
return resp
|
||||
|
||||
async def __aenter__(self):
|
||||
self._obj = await self._coro
|
||||
return self._obj
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
self._obj.close()
|
||||
self._obj = None
|
||||
|
||||
|
||||
class AiofilesContextManager(_ContextManager):
|
||||
"""An adjusted async context manager for aiofiles."""
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
await self._obj.close()
|
||||
self._obj = None
|
@ -1,25 +0,0 @@
|
||||
"""Async executor versions of file functions from the os module."""
|
||||
import asyncio
|
||||
from functools import partial, wraps
|
||||
import os
|
||||
|
||||
|
||||
def wrap(func):
|
||||
@wraps(func)
|
||||
async def run(*args, loop=None, executor=None, **kwargs):
|
||||
if loop is None:
|
||||
loop = asyncio.get_event_loop()
|
||||
pfunc = partial(func, *args, **kwargs)
|
||||
return await loop.run_in_executor(executor, pfunc)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
stat = wrap(os.stat)
|
||||
rename = wrap(os.rename)
|
||||
remove = wrap(os.remove)
|
||||
mkdir = wrap(os.mkdir)
|
||||
rmdir = wrap(os.rmdir)
|
||||
|
||||
if hasattr(os, "sendfile"):
|
||||
sendfile = wrap(os.sendfile)
|
@ -1,108 +0,0 @@
|
||||
"""Handle files using a thread pool executor."""
|
||||
import asyncio
|
||||
from types import coroutine
|
||||
|
||||
from io import (
|
||||
FileIO,
|
||||
TextIOBase,
|
||||
BufferedReader,
|
||||
BufferedWriter,
|
||||
BufferedRandom,
|
||||
)
|
||||
from functools import partial, singledispatch
|
||||
|
||||
from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO
|
||||
from .text import AsyncTextIOWrapper
|
||||
from ..base import AiofilesContextManager
|
||||
|
||||
sync_open = open
|
||||
|
||||
__all__ = ("open",)
|
||||
|
||||
|
||||
def open(
|
||||
file,
|
||||
mode="r",
|
||||
buffering=-1,
|
||||
encoding=None,
|
||||
errors=None,
|
||||
newline=None,
|
||||
closefd=True,
|
||||
opener=None,
|
||||
*,
|
||||
loop=None,
|
||||
executor=None
|
||||
):
|
||||
return AiofilesContextManager(
|
||||
_open(
|
||||
file,
|
||||
mode=mode,
|
||||
buffering=buffering,
|
||||
encoding=encoding,
|
||||
errors=errors,
|
||||
newline=newline,
|
||||
closefd=closefd,
|
||||
opener=opener,
|
||||
loop=loop,
|
||||
executor=executor,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@coroutine
|
||||
def _open(
|
||||
file,
|
||||
mode="r",
|
||||
buffering=-1,
|
||||
encoding=None,
|
||||
errors=None,
|
||||
newline=None,
|
||||
closefd=True,
|
||||
opener=None,
|
||||
*,
|
||||
loop=None,
|
||||
executor=None
|
||||
):
|
||||
"""Open an asyncio file."""
|
||||
if loop is None:
|
||||
loop = asyncio.get_event_loop()
|
||||
cb = partial(
|
||||
sync_open,
|
||||
file,
|
||||
mode=mode,
|
||||
buffering=buffering,
|
||||
encoding=encoding,
|
||||
errors=errors,
|
||||
newline=newline,
|
||||
closefd=closefd,
|
||||
opener=opener,
|
||||
)
|
||||
f = yield from loop.run_in_executor(executor, cb)
|
||||
|
||||
return wrap(f, loop=loop, executor=executor)
|
||||
|
||||
|
||||
@singledispatch
|
||||
def wrap(file, *, loop=None, executor=None):
|
||||
raise TypeError("Unsupported io type: {}.".format(file))
|
||||
|
||||
|
||||
@wrap.register(TextIOBase)
|
||||
def _(file, *, loop=None, executor=None):
|
||||
return AsyncTextIOWrapper(file, loop=loop, executor=executor)
|
||||
|
||||
|
||||
@wrap.register(BufferedWriter)
|
||||
def _(file, *, loop=None, executor=None):
|
||||
return AsyncBufferedIOBase(file, loop=loop, executor=executor)
|
||||
|
||||
|
||||
@wrap.register(BufferedReader)
|
||||
@wrap.register(BufferedRandom)
|
||||
def _(file, *, loop=None, executor=None):
|
||||
return AsyncBufferedReader(file, loop=loop, executor=executor)
|
||||
|
||||
|
||||
@wrap.register(FileIO)
|
||||
def _(file, *, loop=None, executor=None):
|
||||
return AsyncFileIO(file, loop, executor)
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,57 +0,0 @@
|
||||
from ..base import AsyncBase
|
||||
from .utils import (
|
||||
delegate_to_executor,
|
||||
proxy_method_directly,
|
||||
proxy_property_directly,
|
||||
)
|
||||
|
||||
|
||||
@delegate_to_executor(
|
||||
"close",
|
||||
"flush",
|
||||
"isatty",
|
||||
"read",
|
||||
"read1",
|
||||
"readinto",
|
||||
"readline",
|
||||
"readlines",
|
||||
"seek",
|
||||
"seekable",
|
||||
"tell",
|
||||
"truncate",
|
||||
"writable",
|
||||
"write",
|
||||
"writelines",
|
||||
)
|
||||
@proxy_method_directly("detach", "fileno", "readable")
|
||||
@proxy_property_directly("closed", "raw", "name", "mode")
|
||||
class AsyncBufferedIOBase(AsyncBase):
|
||||
"""The asyncio executor version of io.BufferedWriter."""
|
||||
|
||||
|
||||
@delegate_to_executor("peek")
|
||||
class AsyncBufferedReader(AsyncBufferedIOBase):
|
||||
"""The asyncio executor version of io.BufferedReader and Random."""
|
||||
|
||||
|
||||
@delegate_to_executor(
|
||||
"close",
|
||||
"flush",
|
||||
"isatty",
|
||||
"read",
|
||||
"readall",
|
||||
"readinto",
|
||||
"readline",
|
||||
"readlines",
|
||||
"seek",
|
||||
"seekable",
|
||||
"tell",
|
||||
"truncate",
|
||||
"writable",
|
||||
"write",
|
||||
"writelines",
|
||||
)
|
||||
@proxy_method_directly("fileno", "readable")
|
||||
@proxy_property_directly("closed", "name", "mode")
|
||||
class AsyncFileIO(AsyncBase):
|
||||
"""The asyncio executor version of io.FileIO."""
|
@ -1,30 +0,0 @@
|
||||
from ..base import AsyncBase
|
||||
from .utils import (
|
||||
delegate_to_executor,
|
||||
proxy_method_directly,
|
||||
proxy_property_directly,
|
||||
)
|
||||
|
||||
|
||||
@delegate_to_executor(
|
||||
"close",
|
||||
"flush",
|
||||
"isatty",
|
||||
"read",
|
||||
"readable",
|
||||
"readline",
|
||||
"readlines",
|
||||
"seek",
|
||||
"seekable",
|
||||
"tell",
|
||||
"truncate",
|
||||
"write",
|
||||
"writable",
|
||||
"writelines",
|
||||
)
|
||||
@proxy_method_directly("detach", "fileno", "readable")
|
||||
@proxy_property_directly(
|
||||
"buffer", "closed", "encoding", "errors", "line_buffering", "newlines", "name", "mode"
|
||||
)
|
||||
class AsyncTextIOWrapper(AsyncBase):
|
||||
"""The asyncio executor version of io.TextIOWrapper."""
|
@ -1,52 +0,0 @@
|
||||
import functools
|
||||
from types import coroutine
|
||||
|
||||
|
||||
def delegate_to_executor(*attrs):
|
||||
def cls_builder(cls):
|
||||
for attr_name in attrs:
|
||||
setattr(cls, attr_name, _make_delegate_method(attr_name))
|
||||
return cls
|
||||
|
||||
return cls_builder
|
||||
|
||||
|
||||
def proxy_method_directly(*attrs):
|
||||
def cls_builder(cls):
|
||||
for attr_name in attrs:
|
||||
setattr(cls, attr_name, _make_proxy_method(attr_name))
|
||||
return cls
|
||||
|
||||
return cls_builder
|
||||
|
||||
|
||||
def proxy_property_directly(*attrs):
|
||||
def cls_builder(cls):
|
||||
for attr_name in attrs:
|
||||
setattr(cls, attr_name, _make_proxy_property(attr_name))
|
||||
return cls
|
||||
|
||||
return cls_builder
|
||||
|
||||
|
||||
def _make_delegate_method(attr_name):
|
||||
@coroutine
|
||||
def method(self, *args, **kwargs):
|
||||
cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
|
||||
return (yield from self._loop.run_in_executor(self._executor, cb))
|
||||
|
||||
return method
|
||||
|
||||
|
||||
def _make_proxy_method(attr_name):
|
||||
def method(self, *args, **kwargs):
|
||||
return getattr(self._file, attr_name)(*args, **kwargs)
|
||||
|
||||
return method
|
||||
|
||||
|
||||
def _make_proxy_property(attr_name):
|
||||
def proxy_property(self):
|
||||
return getattr(self._file, attr_name)
|
||||
|
||||
return property(proxy_property)
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,429 +0,0 @@
|
||||
# Adafruit MicroPython Tool - Command Line Interface
|
||||
# Author: Tony DiCola
|
||||
# Copyright (c) 2016 Adafruit Industries
|
||||
#
|
||||
# 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.
|
||||
from __future__ import print_function
|
||||
import os
|
||||
import platform
|
||||
import posixpath
|
||||
import re
|
||||
import serial.serialutil
|
||||
|
||||
import click
|
||||
import dotenv
|
||||
|
||||
# Load AMPY_PORT et al from .ampy file
|
||||
# Performed here because we need to beat click's decorators.
|
||||
config = dotenv.find_dotenv(filename=".ampy", usecwd=True)
|
||||
if config:
|
||||
dotenv.load_dotenv(dotenv_path=config)
|
||||
|
||||
import ampy.files as files
|
||||
import ampy.pyboard as pyboard
|
||||
|
||||
|
||||
_board = None
|
||||
|
||||
|
||||
def windows_full_port_name(portname):
|
||||
# Helper function to generate proper Windows COM port paths. Apparently
|
||||
# Windows requires COM ports above 9 to have a special path, where ports below
|
||||
# 9 are just referred to by COM1, COM2, etc. (wacky!) See this post for
|
||||
# more info and where this code came from:
|
||||
# http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/
|
||||
m = re.match("^COM(\d+)$", portname)
|
||||
if m and int(m.group(1)) < 10:
|
||||
return portname
|
||||
else:
|
||||
return "\\\\.\\{0}".format(portname)
|
||||
|
||||
|
||||
@click.group()
|
||||
@click.option(
|
||||
"--port",
|
||||
"-p",
|
||||
envvar="AMPY_PORT",
|
||||
required=True,
|
||||
type=click.STRING,
|
||||
help="Name of serial port for connected board. Can optionally specify with AMPY_PORT environment variable.",
|
||||
metavar="PORT",
|
||||
)
|
||||
@click.option(
|
||||
"--baud",
|
||||
"-b",
|
||||
envvar="AMPY_BAUD",
|
||||
default=115200,
|
||||
type=click.INT,
|
||||
help="Baud rate for the serial connection (default 115200). Can optionally specify with AMPY_BAUD environment variable.",
|
||||
metavar="BAUD",
|
||||
)
|
||||
@click.option(
|
||||
"--delay",
|
||||
"-d",
|
||||
envvar="AMPY_DELAY",
|
||||
default=0,
|
||||
type=click.FLOAT,
|
||||
help="Delay in seconds before entering RAW MODE (default 0). Can optionally specify with AMPY_DELAY environment variable.",
|
||||
metavar="DELAY",
|
||||
)
|
||||
@click.version_option()
|
||||
def cli(port, baud, delay):
|
||||
"""ampy - Adafruit MicroPython Tool
|
||||
|
||||
Ampy is a tool to control MicroPython boards over a serial connection. Using
|
||||
ampy you can manipulate files on the board's internal filesystem and even run
|
||||
scripts.
|
||||
"""
|
||||
global _board
|
||||
# On Windows fix the COM port path name for ports above 9 (see comment in
|
||||
# windows_full_port_name function).
|
||||
if platform.system() == "Windows":
|
||||
port = windows_full_port_name(port)
|
||||
_board = pyboard.Pyboard(port, baudrate=baud, rawdelay=delay)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("remote_file")
|
||||
@click.argument("local_file", type=click.File("wb"), required=False)
|
||||
def get(remote_file, local_file):
|
||||
"""
|
||||
Retrieve a file from the board.
|
||||
|
||||
Get will download a file from the board and print its contents or save it
|
||||
locally. You must pass at least one argument which is the path to the file
|
||||
to download from the board. If you don't specify a second argument then
|
||||
the file contents will be printed to standard output. However if you pass
|
||||
a file name as the second argument then the contents of the downloaded file
|
||||
will be saved to that file (overwriting anything inside it!).
|
||||
|
||||
For example to retrieve the boot.py and print it out run:
|
||||
|
||||
ampy --port /board/serial/port get boot.py
|
||||
|
||||
Or to get main.py and save it as main.py locally run:
|
||||
|
||||
ampy --port /board/serial/port get main.py main.py
|
||||
"""
|
||||
# Get the file contents.
|
||||
board_files = files.Files(_board)
|
||||
contents = board_files.get(remote_file)
|
||||
# Print the file out if no local file was provided, otherwise save it.
|
||||
if local_file is None:
|
||||
print(contents.decode("utf-8"))
|
||||
else:
|
||||
local_file.write(contents)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option(
|
||||
"--exists-okay", is_flag=True, help="Ignore if the directory already exists."
|
||||
)
|
||||
@click.argument("directory")
|
||||
def mkdir(directory, exists_okay):
|
||||
"""
|
||||
Create a directory on the board.
|
||||
|
||||
Mkdir will create the specified directory on the board. One argument is
|
||||
required, the full path of the directory to create.
|
||||
|
||||
Note that you cannot recursively create a hierarchy of directories with one
|
||||
mkdir command, instead you must create each parent directory with separate
|
||||
mkdir command calls.
|
||||
|
||||
For example to make a directory under the root called 'code':
|
||||
|
||||
ampy --port /board/serial/port mkdir /code
|
||||
"""
|
||||
# Run the mkdir command.
|
||||
board_files = files.Files(_board)
|
||||
board_files.mkdir(directory, exists_okay=exists_okay)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("directory", default="/")
|
||||
@click.option(
|
||||
"--long_format",
|
||||
"-l",
|
||||
is_flag=True,
|
||||
help="Print long format info including size of files. Note the size of directories is not supported and will show 0 values.",
|
||||
)
|
||||
@click.option(
|
||||
"--recursive",
|
||||
"-r",
|
||||
is_flag=True,
|
||||
help="recursively list all files and (empty) directories.",
|
||||
)
|
||||
def ls(directory, long_format, recursive):
|
||||
"""List contents of a directory on the board.
|
||||
|
||||
Can pass an optional argument which is the path to the directory. The
|
||||
default is to list the contents of the root, /, path.
|
||||
|
||||
For example to list the contents of the root run:
|
||||
|
||||
ampy --port /board/serial/port ls
|
||||
|
||||
Or to list the contents of the /foo/bar directory on the board run:
|
||||
|
||||
ampy --port /board/serial/port ls /foo/bar
|
||||
|
||||
Add the -l or --long_format flag to print the size of files (however note
|
||||
MicroPython does not calculate the size of folders and will show 0 bytes):
|
||||
|
||||
ampy --port /board/serial/port ls -l /foo/bar
|
||||
"""
|
||||
# List each file/directory on a separate line.
|
||||
board_files = files.Files(_board)
|
||||
for f in board_files.ls(directory, long_format=long_format, recursive=recursive):
|
||||
print(f)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("local", type=click.Path(exists=True))
|
||||
@click.argument("remote", required=False)
|
||||
def put(local, remote):
|
||||
"""Put a file or folder and its contents on the board.
|
||||
|
||||
Put will upload a local file or folder to the board. If the file already
|
||||
exists on the board it will be overwritten with no warning! You must pass
|
||||
at least one argument which is the path to the local file/folder to
|
||||
upload. If the item to upload is a folder then it will be copied to the
|
||||
board recursively with its entire child structure. You can pass a second
|
||||
optional argument which is the path and name of the file/folder to put to
|
||||
on the connected board.
|
||||
|
||||
For example to upload a main.py from the current directory to the board's
|
||||
root run:
|
||||
|
||||
ampy --port /board/serial/port put main.py
|
||||
|
||||
Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py
|
||||
in the board's root run:
|
||||
|
||||
ampy --port /board/serial/port put ./foo/board_boot.py boot.py
|
||||
|
||||
To upload a local folder adafruit_library and all of its child files/folders
|
||||
as an item under the board's root run:
|
||||
|
||||
ampy --port /board/serial/port put adafruit_library
|
||||
|
||||
Or to put a local folder adafruit_library on the board under the path
|
||||
/lib/adafruit_library on the board run:
|
||||
|
||||
ampy --port /board/serial/port put adafruit_library /lib/adafruit_library
|
||||
"""
|
||||
# Use the local filename if no remote filename is provided.
|
||||
if remote is None:
|
||||
remote = os.path.basename(os.path.abspath(local))
|
||||
# Check if path is a folder and do recursive copy of everything inside it.
|
||||
# Otherwise it's a file and should simply be copied over.
|
||||
if os.path.isdir(local):
|
||||
# Directory copy, create the directory and walk all children to copy
|
||||
# over the files.
|
||||
board_files = files.Files(_board)
|
||||
for parent, child_dirs, child_files in os.walk(local):
|
||||
# Create board filesystem absolute path to parent directory.
|
||||
remote_parent = posixpath.normpath(
|
||||
posixpath.join(remote, os.path.relpath(parent, local))
|
||||
)
|
||||
try:
|
||||
# Create remote parent directory.
|
||||
board_files.mkdir(remote_parent)
|
||||
# Loop through all the files and put them on the board too.
|
||||
for filename in child_files:
|
||||
with open(os.path.join(parent, filename), "rb") as infile:
|
||||
remote_filename = posixpath.join(remote_parent, filename)
|
||||
board_files.put(remote_filename, infile.read())
|
||||
except files.DirectoryExistsError:
|
||||
# Ignore errors for directories that already exist.
|
||||
pass
|
||||
|
||||
else:
|
||||
# File copy, open the file and copy its contents to the board.
|
||||
# Put the file on the board.
|
||||
with open(local, "rb") as infile:
|
||||
board_files = files.Files(_board)
|
||||
board_files.put(remote, infile.read())
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("remote_file")
|
||||
def rm(remote_file):
|
||||
"""Remove a file from the board.
|
||||
|
||||
Remove the specified file from the board's filesystem. Must specify one
|
||||
argument which is the path to the file to delete. Note that this can't
|
||||
delete directories which have files inside them, but can delete empty
|
||||
directories.
|
||||
|
||||
For example to delete main.py from the root of a board run:
|
||||
|
||||
ampy --port /board/serial/port rm main.py
|
||||
"""
|
||||
# Delete the provided file/directory on the board.
|
||||
board_files = files.Files(_board)
|
||||
board_files.rm(remote_file)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option(
|
||||
"--missing-okay", is_flag=True, help="Ignore if the directory does not exist."
|
||||
)
|
||||
@click.argument("remote_folder")
|
||||
def rmdir(remote_folder, missing_okay):
|
||||
"""Forcefully remove a folder and all its children from the board.
|
||||
|
||||
Remove the specified folder from the board's filesystem. Must specify one
|
||||
argument which is the path to the folder to delete. This will delete the
|
||||
directory and ALL of its children recursively, use with caution!
|
||||
|
||||
For example to delete everything under /adafruit_library from the root of a
|
||||
board run:
|
||||
|
||||
ampy --port /board/serial/port rmdir adafruit_library
|
||||
"""
|
||||
# Delete the provided file/directory on the board.
|
||||
board_files = files.Files(_board)
|
||||
board_files.rmdir(remote_folder, missing_okay=missing_okay)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("local_file")
|
||||
@click.option(
|
||||
"--no-output",
|
||||
"-n",
|
||||
is_flag=True,
|
||||
help="Run the code without waiting for it to finish and print output. Use this when running code with main loops that never return.",
|
||||
)
|
||||
def run(local_file, no_output):
|
||||
"""Run a script and print its output.
|
||||
|
||||
Run will send the specified file to the board and execute it immediately.
|
||||
Any output from the board will be printed to the console (note that this is
|
||||
not a 'shell' and you can't send input to the program).
|
||||
|
||||
Note that if your code has a main or infinite loop you should add the --no-output
|
||||
option. This will run the script and immediately exit without waiting for
|
||||
the script to finish and print output.
|
||||
|
||||
For example to run a test.py script and print any output after it finishes:
|
||||
|
||||
ampy --port /board/serial/port run test.py
|
||||
|
||||
Or to run test.py and not wait for it to finish:
|
||||
|
||||
ampy --port /board/serial/port run --no-output test.py
|
||||
"""
|
||||
# Run the provided file and print its output.
|
||||
board_files = files.Files(_board)
|
||||
try:
|
||||
output = board_files.run(local_file, not no_output)
|
||||
if output is not None:
|
||||
print(output.decode("utf-8"), end="")
|
||||
except IOError:
|
||||
click.echo(
|
||||
"Failed to find or read input file: {0}".format(local_file), err=True
|
||||
)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option(
|
||||
"--bootloader", "mode", flag_value="BOOTLOADER", help="Reboot into the bootloader"
|
||||
)
|
||||
@click.option(
|
||||
"--hard",
|
||||
"mode",
|
||||
flag_value="NORMAL",
|
||||
help="Perform a hard reboot, including running init.py",
|
||||
)
|
||||
@click.option(
|
||||
"--repl",
|
||||
"mode",
|
||||
flag_value="SOFT",
|
||||
default=True,
|
||||
help="Perform a soft reboot, entering the REPL [default]",
|
||||
)
|
||||
@click.option(
|
||||
"--safe",
|
||||
"mode",
|
||||
flag_value="SAFE_MODE",
|
||||
help="Perform a safe-mode reboot. User code will not be run and the filesystem will be writeable over USB",
|
||||
)
|
||||
def reset(mode):
|
||||
"""Perform soft reset/reboot of the board.
|
||||
|
||||
Will connect to the board and perform a reset. Depending on the board
|
||||
and firmware, several different types of reset may be supported.
|
||||
|
||||
ampy --port /board/serial/port reset
|
||||
"""
|
||||
_board.enter_raw_repl()
|
||||
if mode == "SOFT":
|
||||
_board.exit_raw_repl()
|
||||
return
|
||||
|
||||
_board.exec_(
|
||||
"""if 1:
|
||||
def on_next_reset(x):
|
||||
try:
|
||||
import microcontroller
|
||||
except:
|
||||
if x == 'NORMAL': return ''
|
||||
return 'Reset mode only supported on CircuitPython'
|
||||
try:
|
||||
microcontroller.on_next_reset(getattr(microcontroller.RunMode, x))
|
||||
except ValueError as e:
|
||||
return str(e)
|
||||
return ''
|
||||
def reset():
|
||||
try:
|
||||
import microcontroller
|
||||
except:
|
||||
import machine as microcontroller
|
||||
microcontroller.reset()
|
||||
"""
|
||||
)
|
||||
r = _board.eval("on_next_reset({})".format(repr(mode)))
|
||||
print("here we are", repr(r))
|
||||
if r:
|
||||
click.echo(r, err=True)
|
||||
return
|
||||
|
||||
try:
|
||||
_board.exec_("reset()")
|
||||
except serial.serialutil.SerialException as e:
|
||||
# An error is expected to occur, as the board should disconnect from
|
||||
# serial when restarted via microcontroller.reset()
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
cli()
|
||||
finally:
|
||||
# Try to ensure the board serial connection is always gracefully closed.
|
||||
if _board is not None:
|
||||
try:
|
||||
_board.close()
|
||||
except:
|
||||
# Swallow errors when attempting to close as it's just a best effort
|
||||
# and shouldn't cause a new error or problem if the connection can't
|
||||
# be closed.
|
||||
pass
|
@ -1,310 +0,0 @@
|
||||
# Adafruit MicroPython Tool - File Operations
|
||||
# Author: Tony DiCola
|
||||
# Copyright (c) 2016 Adafruit Industries
|
||||
#
|
||||
# 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.
|
||||
import ast
|
||||
import textwrap
|
||||
|
||||
from ampy.pyboard import PyboardError
|
||||
|
||||
|
||||
BUFFER_SIZE = 32 # Amount of data to read or write to the serial port at a time.
|
||||
# This is kept small because small chips and USB to serial
|
||||
# bridges usually have very small buffers.
|
||||
|
||||
|
||||
class DirectoryExistsError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Files(object):
|
||||
"""Class to interact with a MicroPython board files over a serial connection.
|
||||
Provides functions for listing, uploading, and downloading files from the
|
||||
board's filesystem.
|
||||
"""
|
||||
|
||||
def __init__(self, pyboard):
|
||||
"""Initialize the MicroPython board files class using the provided pyboard
|
||||
instance. In most cases you should create a Pyboard instance (from
|
||||
pyboard.py) which connects to a board over a serial connection and pass
|
||||
it in, but you can pass in other objects for testing, etc.
|
||||
"""
|
||||
self._pyboard = pyboard
|
||||
|
||||
def get(self, filename):
|
||||
"""Retrieve the contents of the specified file and return its contents
|
||||
as a byte string.
|
||||
"""
|
||||
# Open the file and read it a few bytes at a time and print out the
|
||||
# raw bytes. Be careful not to overload the UART buffer so only write
|
||||
# a few bytes at a time, and don't use print since it adds newlines and
|
||||
# expects string data.
|
||||
command = """
|
||||
import sys
|
||||
with open('{0}', 'rb') as infile:
|
||||
while True:
|
||||
result = infile.read({1})
|
||||
if result == b'':
|
||||
break
|
||||
len = sys.stdout.write(result)
|
||||
""".format(
|
||||
filename, BUFFER_SIZE
|
||||
)
|
||||
self._pyboard.enter_raw_repl()
|
||||
try:
|
||||
out = self._pyboard.exec_(textwrap.dedent(command))
|
||||
except PyboardError as ex:
|
||||
# Check if this is an OSError #2, i.e. file doesn't exist and
|
||||
# rethrow it as something more descriptive.
|
||||
if ex.args[2].decode("utf-8").find("OSError: [Errno 2] ENOENT") != -1:
|
||||
raise RuntimeError("No such file: {0}".format(filename))
|
||||
else:
|
||||
raise ex
|
||||
self._pyboard.exit_raw_repl()
|
||||
return out
|
||||
|
||||
def ls(self, directory="/", long_format=True, recursive=False):
|
||||
"""List the contents of the specified directory (or root if none is
|
||||
specified). Returns a list of strings with the names of files in the
|
||||
specified directory. If long_format is True then a list of 2-tuples
|
||||
with the name and size (in bytes) of the item is returned. Note that
|
||||
it appears the size of directories is not supported by MicroPython and
|
||||
will always return 0 (i.e. no recursive size computation).
|
||||
"""
|
||||
|
||||
# Disabling for now, see https://github.com/adafruit/ampy/issues/55.
|
||||
# # Make sure directory ends in a slash.
|
||||
# if not directory.endswith("/"):
|
||||
# directory += "/"
|
||||
|
||||
# Make sure directory starts with slash, for consistency.
|
||||
if not directory.startswith("/"):
|
||||
directory = "/" + directory
|
||||
|
||||
command = """\
|
||||
try:
|
||||
import os
|
||||
except ImportError:
|
||||
import uos as os\n"""
|
||||
|
||||
if recursive:
|
||||
command += """\
|
||||
def listdir(directory):
|
||||
result = set()
|
||||
|
||||
def _listdir(dir_or_file):
|
||||
try:
|
||||
# if its a directory, then it should provide some children.
|
||||
children = os.listdir(dir_or_file)
|
||||
except OSError:
|
||||
# probably a file. run stat() to confirm.
|
||||
os.stat(dir_or_file)
|
||||
result.add(dir_or_file)
|
||||
else:
|
||||
# probably a directory, add to result if empty.
|
||||
if children:
|
||||
# queue the children to be dealt with in next iteration.
|
||||
for child in children:
|
||||
# create the full path.
|
||||
if dir_or_file == '/':
|
||||
next = dir_or_file + child
|
||||
else:
|
||||
next = dir_or_file + '/' + child
|
||||
|
||||
_listdir(next)
|
||||
else:
|
||||
result.add(dir_or_file)
|
||||
|
||||
_listdir(directory)
|
||||
return sorted(result)\n"""
|
||||
else:
|
||||
command += """\
|
||||
def listdir(directory):
|
||||
if directory == '/':
|
||||
return sorted([directory + f for f in os.listdir(directory)])
|
||||
else:
|
||||
return sorted([directory + '/' + f for f in os.listdir(directory)])\n"""
|
||||
|
||||
# Execute os.listdir() command on the board.
|
||||
if long_format:
|
||||
command += """
|
||||
r = []
|
||||
for f in listdir('{0}'):
|
||||
size = os.stat(f)[6]
|
||||
r.append('{{0}} - {{1}} bytes'.format(f, size))
|
||||
print(r)
|
||||
""".format(
|
||||
directory
|
||||
)
|
||||
else:
|
||||
command += """
|
||||
print(listdir('{0}'))
|
||||
""".format(
|
||||
directory
|
||||
)
|
||||
self._pyboard.enter_raw_repl()
|
||||
try:
|
||||
out = self._pyboard.exec_(textwrap.dedent(command))
|
||||
except PyboardError as ex:
|
||||
# Check if this is an OSError #2, i.e. directory doesn't exist and
|
||||
# rethrow it as something more descriptive.
|
||||
if ex.args[2].decode("utf-8").find("OSError: [Errno 2] ENOENT") != -1:
|
||||
raise RuntimeError("No such directory: {0}".format(directory))
|
||||
else:
|
||||
raise ex
|
||||
self._pyboard.exit_raw_repl()
|
||||
# Parse the result list and return it.
|
||||
return ast.literal_eval(out.decode("utf-8"))
|
||||
|
||||
def mkdir(self, directory, exists_okay=False):
|
||||
"""Create the specified directory. Note this cannot create a recursive
|
||||
hierarchy of directories, instead each one should be created separately.
|
||||
"""
|
||||
# Execute os.mkdir command on the board.
|
||||
command = """
|
||||
try:
|
||||
import os
|
||||
except ImportError:
|
||||
import uos as os
|
||||
os.mkdir('{0}')
|
||||
""".format(
|
||||
directory
|
||||
)
|
||||
self._pyboard.enter_raw_repl()
|
||||
try:
|
||||
out = self._pyboard.exec_(textwrap.dedent(command))
|
||||
except PyboardError as ex:
|
||||
# Check if this is an OSError #17, i.e. directory already exists.
|
||||
if ex.args[2].decode("utf-8").find("OSError: [Errno 17] EEXIST") != -1:
|
||||
if not exists_okay:
|
||||
raise DirectoryExistsError(
|
||||
"Directory already exists: {0}".format(directory)
|
||||
)
|
||||
else:
|
||||
raise ex
|
||||
self._pyboard.exit_raw_repl()
|
||||
|
||||
def put(self, filename, data):
|
||||
"""Create or update the specified file with the provided data.
|
||||
"""
|
||||
# Open the file for writing on the board and write chunks of data.
|
||||
self._pyboard.enter_raw_repl()
|
||||
self._pyboard.exec_("f = open('{0}', 'wb')".format(filename))
|
||||
size = len(data)
|
||||
# Loop through and write a buffer size chunk of data at a time.
|
||||
for i in range(0, size, BUFFER_SIZE):
|
||||
chunk_size = min(BUFFER_SIZE, size - i)
|
||||
chunk = repr(data[i : i + chunk_size])
|
||||
# Make sure to send explicit byte strings (handles python 2 compatibility).
|
||||
if not chunk.startswith("b"):
|
||||
chunk = "b" + chunk
|
||||
self._pyboard.exec_("f.write({0})".format(chunk))
|
||||
self._pyboard.exec_("f.close()")
|
||||
self._pyboard.exit_raw_repl()
|
||||
|
||||
def rm(self, filename):
|
||||
"""Remove the specified file or directory."""
|
||||
command = """
|
||||
try:
|
||||
import os
|
||||
except ImportError:
|
||||
import uos as os
|
||||
os.remove('{0}')
|
||||
""".format(
|
||||
filename
|
||||
)
|
||||
self._pyboard.enter_raw_repl()
|
||||
try:
|
||||
out = self._pyboard.exec_(textwrap.dedent(command))
|
||||
except PyboardError as ex:
|
||||
message = ex.args[2].decode("utf-8")
|
||||
# Check if this is an OSError #2, i.e. file/directory doesn't exist
|
||||
# and rethrow it as something more descriptive.
|
||||
if message.find("OSError: [Errno 2] ENOENT") != -1:
|
||||
raise RuntimeError("No such file/directory: {0}".format(filename))
|
||||
# Check for OSError #13, the directory isn't empty.
|
||||
if message.find("OSError: [Errno 13] EACCES") != -1:
|
||||
raise RuntimeError("Directory is not empty: {0}".format(filename))
|
||||
else:
|
||||
raise ex
|
||||
self._pyboard.exit_raw_repl()
|
||||
|
||||
def rmdir(self, directory, missing_okay=False):
|
||||
"""Forcefully remove the specified directory and all its children."""
|
||||
# Build a script to walk an entire directory structure and delete every
|
||||
# file and subfolder. This is tricky because MicroPython has no os.walk
|
||||
# or similar function to walk folders, so this code does it manually
|
||||
# with recursion and changing directories. For each directory it lists
|
||||
# the files and deletes everything it can, i.e. all the files. Then
|
||||
# it lists the files again and assumes they are directories (since they
|
||||
# couldn't be deleted in the first pass) and recursively clears those
|
||||
# subdirectories. Finally when finished clearing all the children the
|
||||
# parent directory is deleted.
|
||||
command = """
|
||||
try:
|
||||
import os
|
||||
except ImportError:
|
||||
import uos as os
|
||||
def rmdir(directory):
|
||||
os.chdir(directory)
|
||||
for f in os.listdir():
|
||||
try:
|
||||
os.remove(f)
|
||||
except OSError:
|
||||
pass
|
||||
for f in os.listdir():
|
||||
rmdir(f)
|
||||
os.chdir('..')
|
||||
os.rmdir(directory)
|
||||
rmdir('{0}')
|
||||
""".format(
|
||||
directory
|
||||
)
|
||||
self._pyboard.enter_raw_repl()
|
||||
try:
|
||||
out = self._pyboard.exec_(textwrap.dedent(command))
|
||||
except PyboardError as ex:
|
||||
message = ex.args[2].decode("utf-8")
|
||||
# Check if this is an OSError #2, i.e. directory doesn't exist
|
||||
# and rethrow it as something more descriptive.
|
||||
if message.find("OSError: [Errno 2] ENOENT") != -1:
|
||||
if not missing_okay:
|
||||
raise RuntimeError("No such directory: {0}".format(directory))
|
||||
else:
|
||||
raise ex
|
||||
self._pyboard.exit_raw_repl()
|
||||
|
||||
def run(self, filename, wait_output=True):
|
||||
"""Run the provided script and return its output. If wait_output is True
|
||||
(default) then wait for the script to finish and then print its output,
|
||||
otherwise just run the script and don't wait for any output.
|
||||
"""
|
||||
self._pyboard.enter_raw_repl()
|
||||
out = None
|
||||
if wait_output:
|
||||
# Run the file and wait for output to return.
|
||||
out = self._pyboard.execfile(filename)
|
||||
else:
|
||||
# Read the file and run it using lower level pyboard functions that
|
||||
# won't wait for it to finish or return output.
|
||||
with open(filename, "rb") as infile:
|
||||
self._pyboard.exec_raw_no_follow(infile.read())
|
||||
self._pyboard.exit_raw_repl()
|
||||
return out
|
@ -1,343 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
pyboard interface
|
||||
|
||||
This module provides the Pyboard class, used to communicate with and
|
||||
control the pyboard over a serial USB connection.
|
||||
|
||||
Example usage:
|
||||
|
||||
import pyboard
|
||||
pyb = pyboard.Pyboard('/dev/ttyACM0')
|
||||
|
||||
Or:
|
||||
|
||||
pyb = pyboard.Pyboard('192.168.1.1')
|
||||
|
||||
Then:
|
||||
|
||||
pyb.enter_raw_repl()
|
||||
pyb.exec('pyb.LED(1).on()')
|
||||
pyb.exit_raw_repl()
|
||||
|
||||
Note: if using Python2 then pyb.exec must be written as pyb.exec_.
|
||||
To run a script from the local machine on the board and print out the results:
|
||||
|
||||
import pyboard
|
||||
pyboard.execfile('test.py', device='/dev/ttyACM0')
|
||||
|
||||
This script can also be run directly. To execute a local script, use:
|
||||
|
||||
./pyboard.py test.py
|
||||
|
||||
Or:
|
||||
|
||||
python pyboard.py test.py
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
_rawdelay = None
|
||||
|
||||
try:
|
||||
stdout = sys.stdout.buffer
|
||||
except AttributeError:
|
||||
# Python2 doesn't have buffer attr
|
||||
stdout = sys.stdout
|
||||
|
||||
def stdout_write_bytes(b):
|
||||
b = b.replace(b"\x04", b"")
|
||||
stdout.write(b)
|
||||
stdout.flush()
|
||||
|
||||
class PyboardError(BaseException):
|
||||
pass
|
||||
|
||||
class TelnetToSerial:
|
||||
def __init__(self, ip, user, password, read_timeout=None):
|
||||
import telnetlib
|
||||
self.tn = telnetlib.Telnet(ip, timeout=15)
|
||||
self.read_timeout = read_timeout
|
||||
if b'Login as:' in self.tn.read_until(b'Login as:', timeout=read_timeout):
|
||||
self.tn.write(bytes(user, 'ascii') + b"\r\n")
|
||||
|
||||
if b'Password:' in self.tn.read_until(b'Password:', timeout=read_timeout):
|
||||
# needed because of internal implementation details of the telnet server
|
||||
time.sleep(0.2)
|
||||
self.tn.write(bytes(password, 'ascii') + b"\r\n")
|
||||
|
||||
if b'for more information.' in self.tn.read_until(b'Type "help()" for more information.', timeout=read_timeout):
|
||||
# login succesful
|
||||
from collections import deque
|
||||
self.fifo = deque()
|
||||
return
|
||||
|
||||
raise PyboardError('Failed to establish a telnet connection with the board')
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.tn.close()
|
||||
except:
|
||||
# the telnet object might not exist yet, so ignore this one
|
||||
pass
|
||||
|
||||
def read(self, size=1):
|
||||
while len(self.fifo) < size:
|
||||
timeout_count = 0
|
||||
data = self.tn.read_eager()
|
||||
if len(data):
|
||||
self.fifo.extend(data)
|
||||
timeout_count = 0
|
||||
else:
|
||||
time.sleep(0.25)
|
||||
if self.read_timeout is not None and timeout_count > 4 * self.read_timeout:
|
||||
break
|
||||
timeout_count += 1
|
||||
|
||||
data = b''
|
||||
while len(data) < size and len(self.fifo) > 0:
|
||||
data += bytes([self.fifo.popleft()])
|
||||
return data
|
||||
|
||||
def write(self, data):
|
||||
self.tn.write(data)
|
||||
return len(data)
|
||||
|
||||
def inWaiting(self):
|
||||
n_waiting = len(self.fifo)
|
||||
if not n_waiting:
|
||||
data = self.tn.read_eager()
|
||||
self.fifo.extend(data)
|
||||
return len(data)
|
||||
else:
|
||||
return n_waiting
|
||||
|
||||
class Pyboard:
|
||||
def __init__(self, device, baudrate=115200, user='micro', password='python', wait=0, rawdelay=0):
|
||||
global _rawdelay
|
||||
_rawdelay = rawdelay
|
||||
if device and device[0].isdigit() and device[-1].isdigit() and device.count('.') == 3:
|
||||
# device looks like an IP address
|
||||
self.serial = TelnetToSerial(device, user, password, read_timeout=10)
|
||||
else:
|
||||
import serial
|
||||
delayed = False
|
||||
for attempt in range(wait + 1):
|
||||
try:
|
||||
self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1)
|
||||
break
|
||||
except (OSError, IOError): # Py2 and Py3 have different errors
|
||||
if wait == 0:
|
||||
continue
|
||||
if attempt == 0:
|
||||
sys.stdout.write('Waiting {} seconds for pyboard '.format(wait))
|
||||
delayed = True
|
||||
time.sleep(1)
|
||||
sys.stdout.write('.')
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
if delayed:
|
||||
print('')
|
||||
raise PyboardError('failed to access ' + device)
|
||||
if delayed:
|
||||
print('')
|
||||
|
||||
def close(self):
|
||||
self.serial.close()
|
||||
|
||||
def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None):
|
||||
data = self.serial.read(min_num_bytes)
|
||||
if data_consumer:
|
||||
data_consumer(data)
|
||||
timeout_count = 0
|
||||
while True:
|
||||
if data.endswith(ending):
|
||||
break
|
||||
elif self.serial.inWaiting() > 0:
|
||||
new_data = self.serial.read(1)
|
||||
data = data + new_data
|
||||
if data_consumer:
|
||||
data_consumer(new_data)
|
||||
timeout_count = 0
|
||||
else:
|
||||
timeout_count += 1
|
||||
if timeout is not None and timeout_count >= 100 * timeout:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
return data
|
||||
|
||||
def enter_raw_repl(self):
|
||||
# Brief delay before sending RAW MODE char if requests
|
||||
if _rawdelay > 0:
|
||||
time.sleep(_rawdelay)
|
||||
|
||||
self.serial.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program
|
||||
|
||||
# flush input (without relying on serial.flushInput())
|
||||
n = self.serial.inWaiting()
|
||||
while n > 0:
|
||||
self.serial.read(n)
|
||||
n = self.serial.inWaiting()
|
||||
|
||||
self.serial.write(b'\r\x01') # ctrl-A: enter raw REPL
|
||||
data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n>')
|
||||
if not data.endswith(b'raw REPL; CTRL-B to exit\r\n>'):
|
||||
print(data)
|
||||
raise PyboardError('could not enter raw repl')
|
||||
|
||||
self.serial.write(b'\x04') # ctrl-D: soft reset
|
||||
data = self.read_until(1, b'soft reboot\r\n')
|
||||
if not data.endswith(b'soft reboot\r\n'):
|
||||
print(data)
|
||||
raise PyboardError('could not enter raw repl')
|
||||
# By splitting this into 2 reads, it allows boot.py to print stuff,
|
||||
# which will show up after the soft reboot and before the raw REPL.
|
||||
# Modification from original pyboard.py below:
|
||||
# Add a small delay and send Ctrl-C twice after soft reboot to ensure
|
||||
# any main program loop in main.py is interrupted.
|
||||
time.sleep(0.5)
|
||||
self.serial.write(b'\x03')
|
||||
time.sleep(0.1) # (slight delay before second interrupt
|
||||
self.serial.write(b'\x03')
|
||||
# End modification above.
|
||||
data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n')
|
||||
if not data.endswith(b'raw REPL; CTRL-B to exit\r\n'):
|
||||
print(data)
|
||||
raise PyboardError('could not enter raw repl')
|
||||
|
||||
def exit_raw_repl(self):
|
||||
self.serial.write(b'\r\x02') # ctrl-B: enter friendly REPL
|
||||
|
||||
def follow(self, timeout, data_consumer=None):
|
||||
# wait for normal output
|
||||
data = self.read_until(1, b'\x04', timeout=timeout, data_consumer=data_consumer)
|
||||
if not data.endswith(b'\x04'):
|
||||
raise PyboardError('timeout waiting for first EOF reception')
|
||||
data = data[:-1]
|
||||
|
||||
# wait for error output
|
||||
data_err = self.read_until(1, b'\x04', timeout=timeout)
|
||||
if not data_err.endswith(b'\x04'):
|
||||
raise PyboardError('timeout waiting for second EOF reception')
|
||||
data_err = data_err[:-1]
|
||||
|
||||
# return normal and error output
|
||||
return data, data_err
|
||||
|
||||
def exec_raw_no_follow(self, command):
|
||||
if isinstance(command, bytes):
|
||||
command_bytes = command
|
||||
else:
|
||||
command_bytes = bytes(command, encoding='utf8')
|
||||
|
||||
# check we have a prompt
|
||||
data = self.read_until(1, b'>')
|
||||
if not data.endswith(b'>'):
|
||||
raise PyboardError('could not enter raw repl')
|
||||
|
||||
# write command
|
||||
for i in range(0, len(command_bytes), 256):
|
||||
self.serial.write(command_bytes[i:min(i + 256, len(command_bytes))])
|
||||
time.sleep(0.01)
|
||||
self.serial.write(b'\x04')
|
||||
|
||||
# check if we could exec command
|
||||
data = self.serial.read(2)
|
||||
if data != b'OK':
|
||||
raise PyboardError('could not exec command')
|
||||
|
||||
def exec_raw(self, command, timeout=10, data_consumer=None):
|
||||
self.exec_raw_no_follow(command);
|
||||
return self.follow(timeout, data_consumer)
|
||||
|
||||
def eval(self, expression):
|
||||
ret = self.exec_('print({})'.format(expression))
|
||||
ret = ret.strip()
|
||||
return ret
|
||||
|
||||
def exec_(self, command):
|
||||
ret, ret_err = self.exec_raw(command)
|
||||
if ret_err:
|
||||
raise PyboardError('exception', ret, ret_err)
|
||||
return ret
|
||||
|
||||
def execfile(self, filename):
|
||||
with open(filename, 'rb') as f:
|
||||
pyfile = f.read()
|
||||
return self.exec_(pyfile)
|
||||
|
||||
def get_time(self):
|
||||
t = str(self.eval('pyb.RTC().datetime()'), encoding='utf8')[1:-1].split(', ')
|
||||
return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6])
|
||||
|
||||
# in Python2 exec is a keyword so one must use "exec_"
|
||||
# but for Python3 we want to provide the nicer version "exec"
|
||||
setattr(Pyboard, "exec", Pyboard.exec_)
|
||||
|
||||
def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', password='python'):
|
||||
pyb = Pyboard(device, baudrate, user, password)
|
||||
pyb.enter_raw_repl()
|
||||
output = pyb.execfile(filename)
|
||||
stdout_write_bytes(output)
|
||||
pyb.exit_raw_repl()
|
||||
pyb.close()
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.')
|
||||
cmd_parser.add_argument('--device', default='/dev/ttyACM0', help='the serial device or the IP address of the pyboard')
|
||||
cmd_parser.add_argument('-b', '--baudrate', default=115200, help='the baud rate of the serial device')
|
||||
cmd_parser.add_argument('-u', '--user', default='micro', help='the telnet login username')
|
||||
cmd_parser.add_argument('-p', '--password', default='python', help='the telnet login password')
|
||||
cmd_parser.add_argument('-c', '--command', help='program passed in as string')
|
||||
cmd_parser.add_argument('-w', '--wait', default=0, type=int, help='seconds to wait for USB connected board to become available')
|
||||
cmd_parser.add_argument('--follow', action='store_true', help='follow the output after running the scripts [default if no scripts given]')
|
||||
cmd_parser.add_argument('files', nargs='*', help='input files')
|
||||
args = cmd_parser.parse_args()
|
||||
|
||||
def execbuffer(buf):
|
||||
try:
|
||||
pyb = Pyboard(args.device, args.baudrate, args.user, args.password, args.wait)
|
||||
pyb.enter_raw_repl()
|
||||
ret, ret_err = pyb.exec_raw(buf, timeout=None, data_consumer=stdout_write_bytes)
|
||||
pyb.exit_raw_repl()
|
||||
pyb.close()
|
||||
except PyboardError as er:
|
||||
print(er)
|
||||
sys.exit(1)
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
if ret_err:
|
||||
stdout_write_bytes(ret_err)
|
||||
sys.exit(1)
|
||||
|
||||
if args.command is not None:
|
||||
execbuffer(args.command.encode('utf-8'))
|
||||
|
||||
for filename in args.files:
|
||||
with open(filename, 'rb') as f:
|
||||
pyfile = f.read()
|
||||
execbuffer(pyfile)
|
||||
|
||||
if args.follow or (args.command is None and len(args.files) == 0):
|
||||
try:
|
||||
pyb = Pyboard(args.device, args.baudrate, args.user, args.password, args.wait)
|
||||
ret, ret_err = pyb.follow(timeout=None, data_consumer=stdout_write_bytes)
|
||||
pyb.close()
|
||||
except PyboardError as er:
|
||||
print(er)
|
||||
sys.exit(1)
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
if ret_err:
|
||||
stdout_write_bytes(ret_err)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1 +0,0 @@
|
||||
pip
|
@ -1,21 +0,0 @@
|
||||
This packge contains a modified version of ca-bundle.crt:
|
||||
|
||||
ca-bundle.crt -- Bundle of CA Root Certificates
|
||||
|
||||
Certificate data from Mozilla as of: Thu Nov 3 19:04:19 2011#
|
||||
This is a bundle of X.509 certificates of public Certificate Authorities
|
||||
(CA). These were automatically extracted from Mozilla's root certificates
|
||||
file (certdata.txt). This file can be found in the mozilla source tree:
|
||||
http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1#
|
||||
It contains the certificates in PEM format and therefore
|
||||
can be directly used with curl / libcurl / php_curl, or with
|
||||
an Apache+mod_ssl webserver for SSL client authentication.
|
||||
Just configure this file as the SSLCACertificateFile.#
|
||||
|
||||
***** BEGIN LICENSE BLOCK *****
|
||||
This Source Code Form is subject to the terms of the Mozilla Public License,
|
||||
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
|
||||
one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
***** END LICENSE BLOCK *****
|
||||
@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $
|
@ -1,83 +0,0 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: certifi
|
||||
Version: 2020.12.5
|
||||
Summary: Python package for providing Mozilla's CA Bundle.
|
||||
Home-page: https://certifiio.readthedocs.io/en/latest/
|
||||
Author: Kenneth Reitz
|
||||
Author-email: me@kennethreitz.com
|
||||
License: MPL-2.0
|
||||
Project-URL: Documentation, https://certifiio.readthedocs.io/en/latest/
|
||||
Project-URL: Source, https://github.com/certifi/python-certifi
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
|
||||
Classifier: Natural Language :: English
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.3
|
||||
Classifier: Programming Language :: Python :: 3.4
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
|
||||
Certifi: Python SSL Certificates
|
||||
================================
|
||||
|
||||
`Certifi`_ provides Mozilla's carefully curated collection of Root Certificates for
|
||||
validating the trustworthiness of SSL certificates while verifying the identity
|
||||
of TLS hosts. It has been extracted from the `Requests`_ project.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
``certifi`` is available on PyPI. Simply install it with ``pip``::
|
||||
|
||||
$ pip install certifi
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
To reference the installed certificate authority (CA) bundle, you can use the
|
||||
built-in function::
|
||||
|
||||
>>> import certifi
|
||||
|
||||
>>> certifi.where()
|
||||
'/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
|
||||
|
||||
Or from the command line::
|
||||
|
||||
$ python -m certifi
|
||||
/usr/local/lib/python3.7/site-packages/certifi/cacert.pem
|
||||
|
||||
Enjoy!
|
||||
|
||||
1024-bit Root Certificates
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Browsers and certificate authorities have concluded that 1024-bit keys are
|
||||
unacceptably weak for certificates, particularly root certificates. For this
|
||||
reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its
|
||||
bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key)
|
||||
certificate from the same CA. Because Mozilla removed these certificates from
|
||||
its bundle, ``certifi`` removed them as well.
|
||||
|
||||
In previous versions, ``certifi`` provided the ``certifi.old_where()`` function
|
||||
to intentionally re-add the 1024-bit roots back into your bundle. This was not
|
||||
recommended in production and therefore was removed at the end of 2018.
|
||||
|
||||
.. _`Certifi`: https://certifiio.readthedocs.io/en/latest/
|
||||
.. _`Requests`: https://requests.readthedocs.io/en/master/
|
||||
|
||||
Addition/Removal of Certificates
|
||||
--------------------------------
|
||||
|
||||
Certifi does not support any addition/removal or other modification of the
|
||||
CA trust store content. This project is intended to provide a reliable and
|
||||
highly portable root of trust to python deployments. Look to upstream projects
|
||||
for methods to use alternate trust.
|
||||
|
||||
|
@ -1,13 +0,0 @@
|
||||
certifi-2020.12.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
certifi-2020.12.5.dist-info/LICENSE,sha256=anCkv2sBABbVmmS4rkrY3H9e8W8ftFPMLs13HFo0ETE,1048
|
||||
certifi-2020.12.5.dist-info/METADATA,sha256=SEw5GGHIeBwGwDJsIUaVfEQAc5Jqs_XofOfTX-_kCE0,2994
|
||||
certifi-2020.12.5.dist-info/RECORD,,
|
||||
certifi-2020.12.5.dist-info/WHEEL,sha256=ADKeyaGyKF5DwBNE0sRE5pvW-bSkFMJfBuhzZ3rceP4,110
|
||||
certifi-2020.12.5.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
|
||||
certifi/__init__.py,sha256=SsmdmFHjHCY4VLtqwpp9P_jsOcAuHj-5c5WqoEz-oFg,62
|
||||
certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
|
||||
certifi/__pycache__/__init__.cpython-39.pyc,,
|
||||
certifi/__pycache__/__main__.cpython-39.pyc,,
|
||||
certifi/__pycache__/core.cpython-39.pyc,,
|
||||
certifi/cacert.pem,sha256=u3fxPT--yemLvyislQRrRBlsfY9Vq3cgBh6ZmRqCkZc,263774
|
||||
certifi/core.py,sha256=V0uyxKOYdz6ulDSusclrLmjbPgOXsD0BnEf0SQ7OnoE,2303
|
@ -1,6 +0,0 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.35.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py2-none-any
|
||||
Tag: py3-none-any
|
||||
|
@ -1 +0,0 @@
|
||||
certifi
|
@ -1,3 +0,0 @@
|
||||
from .core import contents, where
|
||||
|
||||
__version__ = "2020.12.05"
|
@ -1,12 +0,0 @@
|
||||
import argparse
|
||||
|
||||
from certifi import contents, where
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-c", "--contents", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.contents:
|
||||
print(contents())
|
||||
else:
|
||||
print(where())
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@ -1,60 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
certifi.py
|
||||
~~~~~~~~~~
|
||||
|
||||
This module returns the installation location of cacert.pem or its contents.
|
||||
"""
|
||||
import os
|
||||
|
||||
try:
|
||||
from importlib.resources import path as get_path, read_text
|
||||
|
||||
_CACERT_CTX = None
|
||||
_CACERT_PATH = None
|
||||
|
||||
def where():
|
||||
# This is slightly terrible, but we want to delay extracting the file
|
||||
# in cases where we're inside of a zipimport situation until someone
|
||||
# actually calls where(), but we don't want to re-extract the file
|
||||
# on every call of where(), so we'll do it once then store it in a
|
||||
# global variable.
|
||||
global _CACERT_CTX
|
||||
global _CACERT_PATH
|
||||
if _CACERT_PATH is None:
|
||||
# This is slightly janky, the importlib.resources API wants you to
|
||||
# manage the cleanup of this file, so it doesn't actually return a
|
||||
# path, it returns a context manager that will give you the path
|
||||
# when you enter it and will do any cleanup when you leave it. In
|
||||
# the common case of not needing a temporary file, it will just
|
||||
# return the file system location and the __exit__() is a no-op.
|
||||
#
|
||||
# We also have to hold onto the actual context manager, because
|
||||
# it will do the cleanup whenever it gets garbage collected, so
|
||||
# we will also store that at the global level as well.
|
||||
_CACERT_CTX = get_path("certifi", "cacert.pem")
|
||||
_CACERT_PATH = str(_CACERT_CTX.__enter__())
|
||||
|
||||
return _CACERT_PATH
|
||||
|
||||
|
||||
except ImportError:
|
||||
# This fallback will work for Python versions prior to 3.7 that lack the
|
||||
# importlib.resources module but relies on the existing `where` function
|
||||
# so won't address issues with environments like PyOxidizer that don't set
|
||||
# __file__ on modules.
|
||||
def read_text(_module, _path, encoding="ascii"):
|
||||
with open(where(), "r", encoding=encoding) as data:
|
||||
return data.read()
|
||||
|
||||
# If we don't have importlib.resources, then we will just do the old logic
|
||||
# of assuming we're on the filesystem and munge the path directly.
|
||||
def where():
|
||||
f = os.path.dirname(__file__)
|
||||
|
||||
return os.path.join(f, "cacert.pem")
|
||||
|
||||
|
||||
def contents():
|
||||
return read_text("certifi", "cacert.pem", encoding="ascii")
|
@ -1 +0,0 @@
|
||||
pip
|
@ -1,504 +0,0 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
|
||||
|
@ -1,101 +0,0 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: chardet
|
||||
Version: 4.0.0
|
||||
Summary: Universal encoding detector for Python 2 and 3
|
||||
Home-page: https://github.com/chardet/chardet
|
||||
Author: Mark Pilgrim
|
||||
Author-email: mark@diveintomark.org
|
||||
Maintainer: Daniel Blanchard
|
||||
Maintainer-email: dan.blanchard@gmail.com
|
||||
License: LGPL
|
||||
Keywords: encoding,i18n,xml
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: Implementation :: CPython
|
||||
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Topic :: Text Processing :: Linguistic
|
||||
Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*
|
||||
|
||||
Chardet: The Universal Character Encoding Detector
|
||||
--------------------------------------------------
|
||||
|
||||
.. image:: https://img.shields.io/travis/chardet/chardet/stable.svg
|
||||
:alt: Build status
|
||||
:target: https://travis-ci.org/chardet/chardet
|
||||
|
||||
.. image:: https://img.shields.io/coveralls/chardet/chardet/stable.svg
|
||||
:target: https://coveralls.io/r/chardet/chardet
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/chardet.svg
|
||||
:target: https://warehouse.python.org/project/chardet/
|
||||
:alt: Latest version on PyPI
|
||||
|
||||
.. image:: https://img.shields.io/pypi/l/chardet.svg
|
||||
:alt: License
|
||||
|
||||
|
||||
Detects
|
||||
- ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants)
|
||||
- Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese)
|
||||
- EUC-JP, SHIFT_JIS, CP932, ISO-2022-JP (Japanese)
|
||||
- EUC-KR, ISO-2022-KR (Korean)
|
||||
- KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic)
|
||||
- ISO-8859-5, windows-1251 (Bulgarian)
|
||||
- ISO-8859-1, windows-1252 (Western European languages)
|
||||
- ISO-8859-7, windows-1253 (Greek)
|
||||
- ISO-8859-8, windows-1255 (Visual and Logical Hebrew)
|
||||
- TIS-620 (Thai)
|
||||
|
||||
.. note::
|
||||
Our ISO-8859-2 and windows-1250 (Hungarian) probers have been temporarily
|
||||
disabled until we can retrain the models.
|
||||
|
||||
Requires Python 2.7 or 3.5+.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Install from `PyPI <https://pypi.org/project/chardet/>`_::
|
||||
|
||||
pip install chardet
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
|
||||
For users, docs are now available at https://chardet.readthedocs.io/.
|
||||
|
||||
Command-line Tool
|
||||
-----------------
|
||||
|
||||
chardet comes with a command-line script which reports on the encodings of one
|
||||
or more files::
|
||||
|
||||
% chardetect somefile someotherfile
|
||||
somefile: windows-1252 with confidence 0.5
|
||||
someotherfile: ascii with confidence 1.0
|
||||
|
||||
About
|
||||
-----
|
||||
|
||||
This is a continuation of Mark Pilgrim's excellent chardet. Previously, two
|
||||
versions needed to be maintained: one that supported python 2.x and one that
|
||||
supported python 3.x. We've recently merged with `Ian Cordasco <https://github.com/sigmavirus24>`_'s
|
||||
`charade <https://github.com/sigmavirus24/charade>`_ fork, so now we have one
|
||||
coherent version that works for Python 2.7+ and 3.4+.
|
||||
|
||||
:maintainer: Dan Blanchard
|
||||
|
||||
|
@ -1,94 +0,0 @@
|
||||
../../../bin/chardetect,sha256=4iMEiT-304mqbhkz6J4ARQYDf7_ZEx1MoGcCUSOaAqg,258
|
||||
chardet-4.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
chardet-4.0.0.dist-info/LICENSE,sha256=YJXp_6d33SKDn3gBqoRbMcntB_PWv4om3F0t7IzMDvM,26432
|
||||
chardet-4.0.0.dist-info/METADATA,sha256=ySYQAE7NPm3LwxgMqFi1zdLQ48mmwMbrJwqAWCtcbH8,3526
|
||||
chardet-4.0.0.dist-info/RECORD,,
|
||||
chardet-4.0.0.dist-info/WHEEL,sha256=ADKeyaGyKF5DwBNE0sRE5pvW-bSkFMJfBuhzZ3rceP4,110
|
||||
chardet-4.0.0.dist-info/entry_points.txt,sha256=fAMmhu5eJ-zAJ-smfqQwRClQ3-nozOCmvJ6-E8lgGJo,60
|
||||
chardet-4.0.0.dist-info/top_level.txt,sha256=AowzBbZy4x8EirABDdJSLJZMkJ_53iIag8xfKR6D7kI,8
|
||||
chardet/__init__.py,sha256=mWZaWmvZkhwfBEAT9O1Y6nRTfKzhT7FHhQTTAujbqUA,3271
|
||||
chardet/__pycache__/__init__.cpython-39.pyc,,
|
||||
chardet/__pycache__/big5freq.cpython-39.pyc,,
|
||||
chardet/__pycache__/big5prober.cpython-39.pyc,,
|
||||
chardet/__pycache__/chardistribution.cpython-39.pyc,,
|
||||
chardet/__pycache__/charsetgroupprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/charsetprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/codingstatemachine.cpython-39.pyc,,
|
||||
chardet/__pycache__/compat.cpython-39.pyc,,
|
||||
chardet/__pycache__/cp949prober.cpython-39.pyc,,
|
||||
chardet/__pycache__/enums.cpython-39.pyc,,
|
||||
chardet/__pycache__/escprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/escsm.cpython-39.pyc,,
|
||||
chardet/__pycache__/eucjpprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/euckrfreq.cpython-39.pyc,,
|
||||
chardet/__pycache__/euckrprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/euctwfreq.cpython-39.pyc,,
|
||||
chardet/__pycache__/euctwprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/gb2312freq.cpython-39.pyc,,
|
||||
chardet/__pycache__/gb2312prober.cpython-39.pyc,,
|
||||
chardet/__pycache__/hebrewprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/jisfreq.cpython-39.pyc,,
|
||||
chardet/__pycache__/jpcntx.cpython-39.pyc,,
|
||||
chardet/__pycache__/langbulgarianmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langgreekmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langhebrewmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langhungarianmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langrussianmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langthaimodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/langturkishmodel.cpython-39.pyc,,
|
||||
chardet/__pycache__/latin1prober.cpython-39.pyc,,
|
||||
chardet/__pycache__/mbcharsetprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/mbcsgroupprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/mbcssm.cpython-39.pyc,,
|
||||
chardet/__pycache__/sbcharsetprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/sbcsgroupprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/sjisprober.cpython-39.pyc,,
|
||||
chardet/__pycache__/universaldetector.cpython-39.pyc,,
|
||||
chardet/__pycache__/utf8prober.cpython-39.pyc,,
|
||||
chardet/__pycache__/version.cpython-39.pyc,,
|
||||
chardet/big5freq.py,sha256=D_zK5GyzoVsRes0HkLJziltFQX0bKCLOrFe9_xDvO_8,31254
|
||||
chardet/big5prober.py,sha256=kBxHbdetBpPe7xrlb-e990iot64g_eGSLd32lB7_h3M,1757
|
||||
chardet/chardistribution.py,sha256=3woWS62KrGooKyqz4zQSnjFbJpa6V7g02daAibTwcl8,9411
|
||||
chardet/charsetgroupprober.py,sha256=GZLReHP6FRRn43hvSOoGCxYamErKzyp6RgOQxVeC3kg,3839
|
||||
chardet/charsetprober.py,sha256=KSmwJErjypyj0bRZmC5F5eM7c8YQgLYIjZXintZNstg,5110
|
||||
chardet/cli/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
||||
chardet/cli/__pycache__/__init__.cpython-39.pyc,,
|
||||
chardet/cli/__pycache__/chardetect.cpython-39.pyc,,
|
||||
chardet/cli/chardetect.py,sha256=kUPeQCi-olObXpOq5MtlKuBn1EU19rkeenAMwxl7URY,2711
|
||||
chardet/codingstatemachine.py,sha256=VYp_6cyyki5sHgXDSZnXW4q1oelHc3cu9AyQTX7uug8,3590
|
||||
chardet/compat.py,sha256=40zr6wICZwknxyuLGGcIOPyve8DTebBCbbvttvnmp5Q,1200
|
||||
chardet/cp949prober.py,sha256=TZ434QX8zzBsnUvL_8wm4AQVTZ2ZkqEEQL_lNw9f9ow,1855
|
||||
chardet/enums.py,sha256=Aimwdb9as1dJKZaFNUH2OhWIVBVd6ZkJJ_WK5sNY8cU,1661
|
||||
chardet/escprober.py,sha256=kkyqVg1Yw3DIOAMJ2bdlyQgUFQhuHAW8dUGskToNWSc,3950
|
||||
chardet/escsm.py,sha256=RuXlgNvTIDarndvllNCk5WZBIpdCxQ0kcd9EAuxUh84,10510
|
||||
chardet/eucjpprober.py,sha256=iD8Jdp0ISRjgjiVN7f0e8xGeQJ5GM2oeZ1dA8nbSeUw,3749
|
||||
chardet/euckrfreq.py,sha256=-7GdmvgWez4-eO4SuXpa7tBiDi5vRXQ8WvdFAzVaSfo,13546
|
||||
chardet/euckrprober.py,sha256=MqFMTQXxW4HbzIpZ9lKDHB3GN8SP4yiHenTmf8g_PxY,1748
|
||||
chardet/euctwfreq.py,sha256=No1WyduFOgB5VITUA7PLyC5oJRNzRyMbBxaKI1l16MA,31621
|
||||
chardet/euctwprober.py,sha256=13p6EP4yRaxqnP4iHtxHOJ6R2zxHq1_m8hTRjzVZ95c,1747
|
||||
chardet/gb2312freq.py,sha256=JX8lsweKLmnCwmk8UHEQsLgkr_rP_kEbvivC4qPOrlc,20715
|
||||
chardet/gb2312prober.py,sha256=gGvIWi9WhDjE-xQXHvNIyrnLvEbMAYgyUSZ65HUfylw,1754
|
||||
chardet/hebrewprober.py,sha256=c3SZ-K7hvyzGY6JRAZxJgwJ_sUS9k0WYkvMY00YBYFo,13838
|
||||
chardet/jisfreq.py,sha256=vpmJv2Bu0J8gnMVRPHMFefTRvo_ha1mryLig8CBwgOg,25777
|
||||
chardet/jpcntx.py,sha256=PYlNqRUQT8LM3cT5FmHGP0iiscFlTWED92MALvBungo,19643
|
||||
chardet/langbulgarianmodel.py,sha256=r6tvOtO8FqhnbWBB5V4czcl1fWM4pB9lGiWQU-8gvsw,105685
|
||||
chardet/langgreekmodel.py,sha256=1cMu2wUgPB8bQ2RbVjR4LNwCCETgQ-Dwo0Eg2_uB11s,99559
|
||||
chardet/langhebrewmodel.py,sha256=urMmJHHIXtCwaWAqy1zEY_4SmwwNzt730bDOtjXzRjs,98764
|
||||
chardet/langhungarianmodel.py,sha256=ODAisvqCfes8B4FeyM_Pg9HY3ZDnEyaCiT4Bxyzoc6w,102486
|
||||
chardet/langrussianmodel.py,sha256=sPqkrBbX0QVwwy6oqRl-x7ERv2J4-zaMoCvLpkSsSJI,131168
|
||||
chardet/langthaimodel.py,sha256=ppoKOGL9OPdj9A4CUyG8R48zbnXt9MN1WXeCYepa6sc,103300
|
||||
chardet/langturkishmodel.py,sha256=H3ldicI_rhlv0r3VFpVWtUL6X30Wy596v7_YHz2sEdg,95934
|
||||
chardet/latin1prober.py,sha256=S2IoORhFk39FEFOlSFWtgVybRiP6h7BlLldHVclNkU8,5370
|
||||
chardet/mbcharsetprober.py,sha256=AR95eFH9vuqSfvLQZN-L5ijea25NOBCoXqw8s5O9xLQ,3413
|
||||
chardet/mbcsgroupprober.py,sha256=h6TRnnYq2OxG1WdD5JOyxcdVpn7dG0q-vB8nWr5mbh4,2012
|
||||
chardet/mbcssm.py,sha256=SY32wVIF3HzcjY3BaEspy9metbNSKxIIB0RKPn7tjpI,25481
|
||||
chardet/metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
chardet/metadata/__pycache__/__init__.cpython-39.pyc,,
|
||||
chardet/metadata/__pycache__/languages.cpython-39.pyc,,
|
||||
chardet/metadata/languages.py,sha256=41tLq3eLSrBEbEVVQpVGFq9K7o1ln9b1HpY1l0hCUQo,19474
|
||||
chardet/sbcharsetprober.py,sha256=nmyMyuxzG87DN6K3Rk2MUzJLMLR69MrWpdnHzOwVUwQ,6136
|
||||
chardet/sbcsgroupprober.py,sha256=hqefQuXmiFyDBArOjujH6hd6WFXlOD1kWCsxDhjx5Vc,4309
|
||||
chardet/sjisprober.py,sha256=IIt-lZj0WJqK4rmUZzKZP4GJlE8KUEtFYVuY96ek5MQ,3774
|
||||
chardet/universaldetector.py,sha256=DpZTXCX0nUHXxkQ9sr4GZxGB_hveZ6hWt3uM94cgWKs,12503
|
||||
chardet/utf8prober.py,sha256=IdD8v3zWOsB8OLiyPi-y_fqwipRFxV9Nc1eKBLSuIEw,2766
|
||||
chardet/version.py,sha256=A4CILFAd8MRVG1HoXPp45iK9RLlWyV73a1EtwE8Tvn8,242
|
@ -1,6 +0,0 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.35.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py2-none-any
|
||||
Tag: py3-none-any
|
||||
|
@ -1,3 +0,0 @@
|
||||
[console_scripts]
|
||||
chardetect = chardet.cli.chardetect:main
|
||||
|
@ -1 +0,0 @@
|
||||
chardet
|
@ -1,83 +0,0 @@
|
||||
######################## BEGIN LICENSE BLOCK ########################
|
||||
# This library is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU Lesser General Public
|
||||
# License as published by the Free Software Foundation; either
|
||||
# version 2.1 of the License, or (at your option) any later version.
|
||||
#
|
||||
# This library is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
# Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public
|
||||
# License along with this library; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
||||
# 02110-1301 USA
|
||||
######################### END LICENSE BLOCK #########################
|
||||
|
||||
|
||||
from .universaldetector import UniversalDetector
|
||||
from .enums import InputState
|
||||
from .version import __version__, VERSION
|
||||
|
||||
|
||||
__all__ = ['UniversalDetector', 'detect', 'detect_all', '__version__', 'VERSION']
|
||||
|
||||
|
||||
def detect(byte_str):
|
||||
"""
|
||||
Detect the encoding of the given byte string.
|
||||
|
||||
:param byte_str: The byte sequence to examine.
|
||||
:type byte_str: ``bytes`` or ``bytearray``
|
||||
"""
|
||||
if not isinstance(byte_str, bytearray):
|
||||
if not isinstance(byte_str, bytes):
|
||||
raise TypeError('Expected object of type bytes or bytearray, got: '
|
||||
'{}'.format(type(byte_str)))
|
||||
else:
|
||||
byte_str = bytearray(byte_str)
|
||||
detector = UniversalDetector()
|
||||
detector.feed(byte_str)
|
||||
return detector.close()
|
||||
|
||||
|
||||
def detect_all(byte_str):
|
||||
"""
|
||||
Detect all the possible encodings of the given byte string.
|
||||
|
||||
:param byte_str: The byte sequence to examine.
|
||||
:type byte_str: ``bytes`` or ``bytearray``
|
||||
"""
|
||||
if not isinstance(byte_str, bytearray):
|
||||
if not isinstance(byte_str, bytes):
|
||||
raise TypeError('Expected object of type bytes or bytearray, got: '
|
||||
'{}'.format(type(byte_str)))
|
||||
else:
|
||||
byte_str = bytearray(byte_str)
|
||||
|
||||
detector = UniversalDetector()
|
||||
detector.feed(byte_str)
|
||||
detector.close()
|
||||
|
||||
if detector._input_state == InputState.HIGH_BYTE:
|
||||
results = []
|
||||
for prober in detector._charset_probers:
|
||||
if prober.get_confidence() > detector.MINIMUM_THRESHOLD:
|
||||
charset_name = prober.charset_name
|
||||
lower_charset_name = prober.charset_name.lower()
|
||||
# Use Windows encoding name instead of ISO-8859 if we saw any
|
||||
# extra Windows-specific bytes
|
||||
if lower_charset_name.startswith('iso-8859'):
|
||||
if detector._has_win_bytes:
|
||||
charset_name = detector.ISO_WIN_MAP.get(lower_charset_name,
|
||||
charset_name)
|
||||
results.append({
|
||||
'encoding': charset_name,
|
||||
'confidence': prober.get_confidence(),
|
||||
'language': prober.language,
|
||||
})
|
||||
if len(results) > 0:
|
||||
return sorted(results, key=lambda result: -result['confidence'])
|
||||
|
||||
return [detector.result]
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user