推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
gosky
V2EX  ›  Python

哪位朋友帮忙用 mac 测试下我的 Python 脚本

  •  
  •   gosky · 9h 33m ago · 885 views

    把输出贴给我
    如果有异常,如果能附带帮忙 fix 更好

    import signal
    import subprocess
    from typing import OrderedDict
    
    APP_NAME = "Hello"
    
    
    class CalledProcessError(subprocess.CalledProcessError):
        """
        `subprocess.CalledProcessError` does not print `stderr` and `output`.
        """
    
        def __str__(self):
            if self.returncode and self.returncode < 0:
                try:
                    return "Command '%s' died with %r." % (
                        self.cmd,
                        signal.Signals(-self.returncode),
                    )
                except ValueError:
                    return "Command '%s' died with unknown signal %d." % (
                        self.cmd,
                        -self.returncode,
                    )
            else:
                return (
                    "Command '%s' returned non-zero exit status %d. stderr: '%s'. output: '%s'"
                    % (self.cmd, self.returncode, self.stderr.strip(), self.output.strip())
                )
    
    
    class DecryptError(Exception): ...
    
    
    class DarwinCryptex:
        scheme = "security"
    
        def encrypt(self, attrs: OrderedDict[str, str], plaintext: str) -> str:
            account = "-".join([f"{k}:{v}" for k, v in attrs.items()])
            cmd = [
                "security",
                "add-generic-password",
                "-a",
                account,
                "-s",
                APP_NAME,
                "-w",
                plaintext,
                "-U",
            ]
            r = subprocess.run(
                cmd,
                capture_output=True,
                encoding="utf-8",
                text=True,
                timeout=5,
            )
            if r.returncode != 0:
                raise CalledProcessError(
                    r.returncode, cmd, output=r.stdout, stderr=r.stderr
                )
            return "******"
    
        def decrypt(self, attrs: OrderedDict[str, str], ciphertext: str) -> str:
            account = "-".join([f"{k}:{v}" for k, v in attrs.items()])
            cmd = [
                "security",
                "find-generic-password",
                "-a",
                account,
                "-s",
                APP_NAME,
                "-w",
            ]
            r = subprocess.run(
                cmd,
                capture_output=True,
                encoding="utf-8",
                text=True,
                timeout=5,
            )
            if r.returncode == 0:
                return r.stdout.strip()
            elif r.returncode == 44:
                raise DecryptError()
            else:
                raise CalledProcessError(
                    r.returncode, cmd, output=r.stdout, stderr=r.stderr
                )
    
        def clean(self, attrs: OrderedDict[str, str]):
            account = "-".join([f"{k}:{v}" for k, v in attrs.items()])
            cmd = ["security", "delete-generic-password", "-a", account, "-s", APP_NAME]
            r = subprocess.run(
                cmd, capture_output=True, encoding="utf-8", text=True, timeout=5
            )
            if r.returncode not in (0, 44):
                raise CalledProcessError(
                    r.returncode, cmd, output=r.stdout, stderr=r.stderr
                )
    
    
    cryptex = DarwinCryptex()
    attrs: OrderedDict[str, str] = OrderedDict(
        [
            ("app", "test"),
            ("section", "hello"),
            ("key", "你好"),
        ]
    )
    plaintext = "Hello world! 你好,世界!"
    
    try:
        ciphertext = cryptex.encrypt(attrs, plaintext)
        decrypted = cryptex.decrypt(attrs, ciphertext)
        assert decrypted == plaintext
    
        mismatch_attrs = attrs.copy()
        mismatch_attrs["needless"] = "有毒"
        try:
            cryptex.decrypt(mismatch_attrs, ciphertext)
        except DecryptError:
            pass
        else:
            raise AssertionError("Expected DecryptError")
    finally:
        cryptex.clean(attrs)
    
    
    Supplement 1  ·  8h 1m ago
    不用了。
    改用 github Action ,薅帝国主义资本家的羊毛
    谢谢各位。
    12 replies    2026-07-10 18:26:27 +08:00
    busln
        1
    busln  
       9h 19m ago
    assert decrypted == plaintext

    不成立报错了

    且 encrypt 是不是没写完全呀
    gosky
        2
    gosky  
    OP
       9h 11m ago
    @busln
    感觉是写完了
    把两个变量都打印瞧瞧?
    busln
        3
    busln  
       8h 59m ago
    程序有问题, 没写进去
    gosky
        4
    gosky  
    OP
       8h 48m ago
    @busln 我用 claude review 了下,没大问题啊
    zhhanging
        5
    zhhanging  
       8h 43m ago
    assert 失败,打印两个变量如下
    decrypted: 48656c6c6f20776f726c642120e4bda0e5a5bdefbc8ce4b896e7958cefbc81
    plaintext: Hello world! 你好,世界!
    应该是遇到非 ascii 字符给他转成 hex 了
    gosky
        6
    gosky  
    OP
       8h 37m ago
    @zhhanging
    "Hello world! 你好,世界!".encode('utf-8').hex()
    刚好是
    '48656c6c6f20776f726c642120e4bda0e5a5bdefbc8ce4b896e7958cefbc81'
    busln
        7
    busln  
       8h 33m ago
    finally 给删了,漏看了
    @gosky
    busln
        8
    busln  
       8h 31m ago
    bytes.fromhex(hex).decode("utf-8")
    这样就能转换回来了
    gosky
        9
    gosky  
    OP
       8h 28m ago
    @busln
    把下面的中文字符,全换成英文字母,会怎么样?

    attrs: OrderedDict[str, str] = OrderedDict(
    [
    ("app", "test"),
    ("section", "hello"),
    ("key", "你好"),
    ]
    )
    plaintext = "Hello world! 你好,世界!"
    keakon
        10
    keakon  
       8h 8m ago
    你在 github 上建个 ci ,让它用 macos 的容器跑不就行了。。
    gosky
        11
    gosky  
    OP
       8h 2m ago
    @keakon 是的。正这么玩着。感谢
    wenrouxiaozhu
        12
    wenrouxiaozhu  
       7h 59m ago
    开虚拟机+黑苹果也行
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1093 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 18:25 · PVG 02:25 · LAX 11:25 · JFK 14:25
    ♥ Do have faith in what you're doing.