V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
Contextualist
V2EX  ›  分享创造

shx: 用 Python 写脚本的利器

  •  
  •   Contextualist ·
    Contextualist · 2021-05-13 08:06:55 +08:00 · 2647 次点击
    这是一个创建于 1072 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近看到 zx,就是那个用 js 写脚本的封装。用上手感觉是不错,但觉得 js 的语法糖不够甜,特别是 Array 的处理。于是乎就照着它的哲学移植到了 Python 上,用法差别不大,就照 asyncio 那套走就行。借用 zx 的示例:

    #!/usr/bin/env shx
    
    await $"cat setup.py | grep name"
    
    branch = (await $("git branch --show-current", capture=True)).stdout
    await $f"dep deploy --branch={branch}"
    
    await gather(
      $"sleep 1; echo 1",
      $"sleep 2; echo 2",
      $"sleep 3; echo 3",
    )
    
    name = "foo bar"
    await $f"mkdir /tmp/{Q(name)}"
    

    $ 符号是用 tokenize 替换的,比较中规中矩吧,大概。(嗯因为我之前试过用 forbiddenfruit 之流的,总有些复杂的情况会 segfault) 然后这也是 Python 里的非法字符,还自带显眼的红色语法高亮呢(逃

    目前项目没有任何依赖,请自带 httpxrequestscoloramatermcolor 什么的。

    匆匆忙忙写的,可能有些 bug 。不过我自己已经用上了,爽就完事儿了。

    项目: https://github.com/Contextualist/shx

    9 条回复    2021-05-18 18:11:12 +08:00
    billzhuang
        1
    billzhuang  
       2021-05-13 09:59:02 +08:00
    牛逼!
    ch2
        2
    ch2  
       2021-05-13 10:05:22 +08:00 via iPhone
    但是,Python 本身就是很好的脚本了
    duhb
        3
    duhb  
       2021-05-13 10:11:33 +08:00 via iPhone
    就这?用 python 或 js 本身就挺好
    clino
        4
    clino  
       2021-05-13 10:13:57 +08:00   ❤️ 2
    我本来最讨厌 hell perl 这种有 $ 的语言,所以写脚本偏好用 python,然后你又在 python 里把$给整了出来,这个让我觉得一阵恶心,觉得 python 被 shell 污染到的样子。。。
    Contextualist
        5
    Contextualist  
    OP
       2021-05-13 10:19:41 +08:00
    @ch2 对,Python 的 pathlib 和 shutil 已经可以进行大部分的文件操作了,但主要是调用外部命令不算方便:subprocess.run 需要预设一些参数,asyncio 的 subprocess 更是缺少一些高级封装。如果拿来日常使用还是需要写一些重复代码的。
    abersheeran
        6
    abersheeran  
       2021-05-13 10:41:56 +08:00
    @Contextualist 以前我也觉得 subprocess.run 不好用。某天我想起来 subprocess 下的 check_call 和 check_output,试了一下,好用的很。
    Contextualist
        7
    Contextualist  
    OP
       2021-05-13 11:10:33 +08:00
    @abersheeran 感谢提出,这两个接口是可以覆盖挺多场景。其实我自己的主要用途还是需要封装异步的接口。
    然后又仔细拜读了一下文档,发现 check_call 和 check_output ( python 3.1 )竟然是先于 subprocess.run ( python 3.5 )的,看来官方倾向于整合成一个高级接口,算是牺牲便捷换取风格统一吧。
    WillBC
        8
    WillBC  
       2021-05-14 11:21:43 +08:00 via iPhone
    ruby 早就自带了这个东西
    sinux
        9
    sinux  
       2021-05-18 18:11:12 +08:00
    对楼主的这个 repo 不评价。
    但是楼上说 zx 没用的....建议把 zx 再好好看看,然后再喷
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1078 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:28 · PVG 07:28 · LAX 16:28 · JFK 19:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.