{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version":"0.2.0", "configurations":[ { "name":"Python: Current File", "type":"python", "request":"launch", "program":"${file}",// the current opened file "console":"integratedTerminal", "env":{}, "args":[], "cwd":"${fileWorkspaceFolder}",// the current opened file's workspace folder "justMyCode":false } ] }
Host myhost HostName 192.168.1.156 User root Port 22
vscode->Remote Explorer->Containers 可以看到主机中运行的容器,右键 Attach to Container,vscode 自动进入容器内部:
安装调试语言插件,ms-python.python
进入调试配置左侧栏,创建基于 Python 调试配置模板,选择 Attach 模板 Attach using Process Id
生成文件 .vscode/launch.json
增加匹配调试服务的端口 port 到 launch.json 文件,port 可从服务路径 configs\default_settings.yaml 找到 attach_port: 12345 # 服务默认 attach 调试端口,或从环境变量 CONF_ATTACH_PORT 中获取最新 port :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version":"0.2.0", "configurations":[ { "name":"Python: Attach using Process Id", "type":"python", "request":"attach", "processId":"${command:pickProcess}", "justMyCode":true, "port":12345 } ] }
defas_const(cls): """成为常量 Example:: from constant import as_const @as_const class _Platform: linux = "linux" windows = "windows" macosx = "macosx" @as_const class _Const: plat = _Platform() ct = _Const() pt = _Platform() print(ct.plat.linux) print(pt.linux) """
classConstError(TypeError): """常量不可改错误定义"""
pass
classConstCaseError(ConstError): """常量大小写错误定义"""
pass
@wraps(cls) defconst_setter(self, key, value):
if key inself.__dict__.keys(): raise ConstError(f"Can't change a const variable with name {key}") ifnot key.isupper(): raise ConstCaseError( f"Const variable must be combined with upper letters:{key}" )
# in pyproject.toml [project] name = "xxx" # version = "0.0.1" # Remove any existing version parameter. dynamic = ["version"] [tool.setuptools_scm] write_to = "xxx/_version.py"
# in pyproject.toml [tool.ruff] select = [ "E", "F", "W", # flake8 "B", # flake8-bugbear "I", # isort "N", # pep8-naming "ARG", # flake8-unused-arguments "C4", # flake8-comprehensions "EM", # flake8-errmsg "ICN", # flake8-import-conventions "ISC", # flake8-implicit-str-concat "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # pylint "PT", # flake8-pytest-style "RET", # flake8-return "RUF100", # Ruff-specific "SIM", # flake8-simplify "UP", # pyupgrade "YTT", # flake8-2020 ] ignore = [ "PLR", # Design related pylint "E501", # Line too long (Black is enough) "PT011", # Too broad with raises in pytest "PT004", # Fixture that doesn't return needs underscore (no, it is fine) "SIM118", # iter(x) is not always the same as iter(x.keys()) "ARG001", # Ignore unused arguments "PLW0603", # We're fine with global vars ] target-version = "py37" src = ["src"] unfixable = ["T20"] exclude = [] # Allow lines to be as long as 120 characters. line-length = 120 isort.known-first-party = ["env", "pybind11_cross_module_tests", "pybind11_tests"]
[tool.ruff.per-file-ignores]# rules on the per file basis include common ignore rules "tests/**" = ["EM", "N"] "tests/test_call_policies.py" = ["PLC1901"]
black
black: 标准化项目格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 每行不超过 120 [tool.black] line-length = 120 target-version = ['py38'] include = '\.pyi?$' exclude = ''' ( /( \.eggs # exclude a few common directories in the | \.git # root of the project | \.mypy_cache | \.venv | _build | build | dist )/ ) '''
# pyproject.toml [tool.codespell] # note: pre-commit passes explicit lists of files here, which this skip file list doesn't override - # this is only to allow you to run codespell interactively skip = "./.git,./.github" # ignore short words, and typename parameters like offset ignore-regex = "\\b(.{1,4}|[A-Z]\\w*T)\\b" # ignore allowed words ignore-words-list = "passing" # use the 'clear' dictionary for unambiguous spelling mistakes builtin = "clear" # disable warnings about binary files and wrong encoding quiet-level = 3
classItemSchema(Schema): """Define serialization protocol for class Item Args: name: str to be registered by the schema price: custom way to be registered date: date to be registered """
name = fields.String() price = fields.Method("price_decimal_2_float", deserialize="float_2_decimal") date = fields.Date()
@post_load # post_load to make the schema deserialized as object-like defmake_item(self, data, **kwargs): return Item(**data)
defprice_decimal_2_float(self, item: Item): """price attr to save""" returnfloat(item.price)
deffloat_2_decimal(self, float): """price attr to load""" return decimal.Decimal(str(float))
Python 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license"for more information. >>> from pytest import ExitCode >>> help(ExitCode) Help on class ExitCode in module _pytest.config:
class ExitCode(enum.IntEnum) | ExitCode(value, names=None, *, module=None, qualname=None, type=None, start=1) | | Encodes the valid exit codes by pytest. | | Currently users and plugins may supply other exit codes as well. | | .. versionadded:: 5.0 | | Method resolution order: | ExitCode | enum.IntEnum | builtins.int | enum.Enum | builtins.object | | Data and other attributes defined here: | | INTERNAL_ERROR = <ExitCode.INTERNAL_ERROR: 3> # 内部发生错误 | | INTERRUPTED = <ExitCode.INTERRUPTED: 2> # 测试过程被用户中断 | | NO_TESTS_COLLECTED = <ExitCode.NO_TESTS_COLLECTED: 5> # 没有实际的运行case | | OK = <ExitCode.OK: 0> # 全部测试case运行成功 | | TESTS_FAILED = <ExitCode.TESTS_FAILED: 1> # 存在测试case失败 | | USAGE_ERROR = <ExitCode.USAGE_ERROR: 4> # pytest命令行使用错误 | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: |
# Run this from the terminal as you would normally start a FastAPI app: `uvicorn run:app` # and navigate to http://localhost:8000/gradio in your browser.
repos: # Black, the code formatter, natively supports pre-commit -repo:https://github.com/psf/black rev:"22.6.0"# Keep in sync with blacken-docs hooks: -id:black
# Also code format the docs -repo:https://github.com/asottile/blacken-docs rev:"v1.12.1" hooks: -id:blacken-docs additional_dependencies: -black==22.6.0# keep in sync with black hook
pre-commit cli
1 2 3 4 5 6 7 8 9 10
# 所有仓库代码都运行 pre-commit run -a # 注册提交阶段执行钩子 pre-commit install --hook-type commit-msg # 卸载相应钩子 pre-commit uninstall --hook-type commit-msg --hook-type pre-commit # 卸载 pre-commit 钩子 pre-commit uninstall # 执行对应配置钩子 black 格式化代码 pre-commit run black
# .pre-commit-config.yaml # To use: # # pre-commit run -a # # Or: # # pre-commit install # (runs every time you commit in git) # # To update this file: # # pre-commit autoupdate # # See https://github.com/pre-commit/pre-commit
# (optional: default false) set to true to have pre-commit stop running hooks after the first failure fail_fast:false
# (optional: default ^$) global file exclude pattern.The below ignores sub/dir1, sub/dir2, *.drawio. exclude:| (?x)( ^(sub/dir1) | ^(sub/dir2) | ^.*\.drawio ) # (optional: default '') global file include pattern. files:''# set '' as default
# A list of repository mappings. repos: # Standard hooks -repo:https://github.com/pre-commit/pre-commit-hooks# the repository url to git clone from # the revision or tag to clone at rev:v4.3.0 hooks: # which hook from the repository to use. -id:check-added-large-files -id:check-case-conflict -id:check-docstring-first -id:check-merge-conflict -id:check-toml -id:debug-statements -id:end-of-file-fixer types_or: [c, c++, cuda, proto, textproto, java, python] -id:mixed-line-ending -id:requirements-txt-fixer -id:trailing-whitespace -id:check-yaml exclude:^deploy(\/[^\/]+)*\/templates\/.*$ -id:check-shebang-scripts-are-executable
# Upgrade old Python syntax -repo:https://github.com/asottile/pyupgrade rev:v2.37.3 hooks: -id:pyupgrade # (optional) list of additional parameters to pass to the hook. args: [--py37-plus]
# Ruff, the Python auto-correcting linter written in Rust, Ruff can be used to # replace Flake8 (plus dozens of plugins), isort, pydocstyle, yesqa, eradicate, # pyupgrade, and autoflake -repo:https://github.com/astral-sh/ruff-pre-commit rev:v0.0.281 hooks: -id:ruff args: # this should be placed after black, isort, and similar # tools when opoen fixing ---fix ---show-fixes
# Another nicely sort includes -repo:https://github.com/timothycrosley/isort rev:5.12.0 hooks: -id:isort additional_dependencies: [toml]
# Black, the code formatter, natively supports pre-commit -repo:https://github.com/psf/black rev:22.6.0# Keep in sync with blacken-docs hooks: -id:black args: ---line-length=88
# Also code format the docs -repo:https://github.com/asottile/blacken-docs rev:v1.12.1 hooks: -id:blacken-docs # (optional) a list of dependencies that will be installed in the environment where this # hook gets run. One useful application is to install plugins for hooks such as eslint. additional_dependencies: -black==22.6.0# keep in sync with black hook
# Black mirror, 2x faster black mirror -repo:https://github.com/psf/black-pre-commit-mirror rev:23.7.0 hooks: -id:black args: ---line-length=88
# Changes tabs to spaces -repo:https://github.com/Lucas-C/pre-commit-hooks rev:v1.3.1 hooks: -id:remove-tabs
# Autoremoves unused imports -repo:https://github.com/hadialqattan/pycln rev:v2.1.1 hooks: -id:pycln # (optional) confines the hook to the commit, merge-commit, push, prepare-commit-msg, # commit-msg, post-checkout, post-commit, post-merge, post-rewrite, or manual stage. # See https://pre-commit.com/#confining-hooks-to-run-at-certain-stages stages: [manual]
# Checking for common mistakes -repo:https://github.com/pre-commit/pygrep-hooks rev:v1.9.0 hooks: -id:python-check-blanket-noqa -id:python-check-blanket-type-ignore -id:python-no-log-warn -id:python-use-type-annotations
# Automatically remove noqa that are not used -repo:https://github.com/asottile/yesqa rev:v1.4.0 hooks: -id:yesqa additional_dependencies:&flake8_dependencies -flake8-bugbear -pep8-naming
# Checks the manifest for missing files (native support) -repo:https://github.com/mgedmin/check-manifest rev:0.48 hooks: -id:check-manifest # This is a slow hook, so only run this if --hook-stage manual is passed stages: [manual] additional_dependencies: [cmake, ninja]
# Check json with comments -repo:https://gitlab.com/bmares/check-json5 rev:v1.0.0 hooks: -id:check-json5
# Check for spelling -repo:https://github.com/codespell-project/codespell rev:v2.2.1 hooks: -id:codespell exclude:| (?x)( ^(package-lock.json) ) args: ---skip=".vscode/" ---ignore-words-list="Transer,transer" ---check-filenames ---write-changes# auto fix in place # using the pyproject.toml as the config file additional_dependencies: -tomli # stages: [manual]
# Check for spelling -repo:https://github.com/crate-ci/typos rev:v1.16.2 hooks: -id:typos
# Check for common shell mistakes -repo:https://github.com/shellcheck-py/shellcheck-py rev:v0.8.0.4 hooks: -id:shellcheck
# Clang format the codebase automatically -repo:https://github.com/pre-commit/mirrors-clang-format rev:v14.0.6 hooks: -id:clang-format # (optional: default []) list of file types to run on (OR). See Filtering files with types. types_or: [c++, c, cuda]
# Commitizen is a tool designed that obeys a standard way of committing rules. -repo:https://github.com/commitizen-tools/commitizen rev:v2.32.1 hooks: -id:commitizen # (optional: default (all stages)) confines the hook to the commit, merge-commit, # push, prepare-commit-msg, commit-msg, post-checkout, post-commit, post-merge, # post-rewrite, or manual stage. See Confining hooks to run at certain stages. stages: [commit-msg] -id:commitizen-branch stages: [push]
# Check for markdown -repo:https://github.com/igorshubovych/markdownlint-cli rev:v0.35.0 hooks: -id:markdownlint-fix # need rc config, such as https://github.com/msclock/blog_hexo/blob/master # related options for rc config, see https://github.com/DavidAnson/markdownlint#optionsconfig
loguru.logger.debug("This is a debug message") loguru.logger.info("This is an info message") loguru.logger.warning("This is a warning message") loguru.logger.error("This is an error message")