Python 遍历指定目录下的文件

列出指定目录下的全部文件,或可以通过扩展名指定文件类型,也可以通过指定排除规则,忽略部分文件。

def list_files(
    dir: str, ext: list = None, recursive: bool = True, excludes: list = None
):
    """
    Args:
        - dir, directory path.
        - ext, file extension list, lowercase letters. Default is None, which means all files.
        - recursive, Default is True, will list files in subfolders.
        - excludes, exclude folder or file name list, regexp pattern string. Default is None, which means all folders

    Tips:
        - How to get relative path of a file: os.path.relpath(file_path, dir_path)
        - How to get only name of a file: os.path.basename(file_path)

    Version:
        v0.2.0
        https://gist.github.com/nodewee/eae12e2b74beb82162b8b488648f1fdd
    """

    for f in os.scandir(dir):
        if excludes:
            is_ignore = False
            for pat in excludes:
                if re.search(pat, f.name):
                    is_ignore = True
                    break
            if is_ignore:
                continue

        if recursive:
            if f.is_dir():
                for item in list_files(f.path, ext, recursive, excludes):
                    yield item

        if f.is_file():
            if ext is None:
                yield f.path
            else:
                if os.path.splitext(f.name)[1].lower() in ext:
                    yield f.path

Code on GitHub Gist

Python 复制文本到剪贴板

目前(Python 3.8)为止,Python 并没有原生支持访问系统剪贴板。

搜寻出有几种方法,梳理如下:

简单有效。但是并不适合复杂环境。

import os
# on macOS
def write_to_clipboard(text):
    command = f"echo '{text}' | pbcopy"
    os.system(command)

def read_from_clipboard():
    command = "pbpaste"
    return os.popen(command).read()

更多 Shell 命令参考:Shell use clipboard to copy and paste

Qt Pyside2 访问剪贴板

Qt/Pyside2 读取系统剪贴板内容

import sys
from PySide2.QtWidgets import QApplication

app = QApplication(sys.argv)
clipboard = app.clipboard()

print(clipboard.mimeData().formats())
print(clipboard.mimeData().data(clipboard.mimeData().formats()[0]))

app.closeAllWindows()
app=None

mimeData() 就和 drag 时对 mimeData() 的操作一样了。

引用自 doc.qt.io:

QClipboard supports the same data types that QDrag does, and uses similar mechanisms. For advanced clipboard usage read Drag and Drop .

JS 自动滚动页面到底部

function getScrollTop() {
    var scrollTop = 0,
        bodyScrollTop = 0,
        documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop =
        bodyScrollTop - documentScrollTop > 0
            ? bodyScrollTop
            : documentScrollTop;
    return scrollTop;
}

function getScrollHeight() {
    var scrollHeight = 0,
        bodyScrollHeight = 0,
        documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight =
        bodyScrollHeight - documentScrollHeight > 0
            ? bodyScrollHeight
            : documentScrollHeight;
    return scrollHeight;
}

function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//
function autoScroll() {
    if (getScrollTop() + getWindowHeight() < getScrollHeight()) {
        window.scrollTo({
            top: window.scrollY + 5,
            behavior: "smooth",
        });
        var timerId = setTimeout(autoScroll, 50);
        // stop when click
        document.addEventListener("click", (event) => {
            window.clearInterval(timerId);
        });
    }
}
autoScroll();

通过浏览器标签(Bookmarklet方式)调用,拖拽下面的链接到浏览器标签栏:

git 统计仓库中代码行数

列出每个文件行数,以及总行数
git ls-files | xargs wc -l

指定文件夹
git ls-files src lib | xargs wc -l
以上示例是指定仓库中 lib 文件夹

过滤文件夹或文件类型
 git ls-files | grep -Ev 'examples|.txt' | xargs wc -l
以上示例是过滤 examples 文件夹和所有 .txt 文件

Python 取列表共有元素(交集)

交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合。

使用 Python 元组数据类型 set 来实现交集操作。

a = [1, 2, 3]
b = [3, 4, 5]
c = set(a).intersection(set(b))
print(list(c))
# [3]

AWS Amplify 删除 APP失败之 Invoking remove all backends execution failed

原因:有 backend environment,需要先删除

一般这时通过 Web Console 删除后端环境也会失败。可以通过 AWS CLI 来删除:
aws amplify delete-backend-environment --app-id YOUR-APP-ID --environment-name ENV-NAME --region YOR-REGION-NAME

  • APP ID 查寻方式:
    App settings -> General, App ARN 的最后部分。例如:
    arn:aws:amplify:ap-southeast-1:YOUR-ACCOUNT-ID:apps/APP-ID

CSS 禁止元素响应鼠标事件

当我们需要某些 DOM 元素不响应鼠标事件时,例如点击(click) 悬停(hover)等, 可以使用 CSS 属性直接实现,方便快捷。

CSS 方法:

div {
	pointer-events: none;
}

如果项目使用 tailwindcss, 可以使用类名: pointer-events-none