代码之家  ›  专栏  ›  技术社区  ›  Tzook Bar Noy

自动执行多个bash命令[关闭]

  •  -1
  • Tzook Bar Noy  · 技术社区  · 6 年前

    对于构建脚本,有没有使用Python实现自动化的适当方法?

    我想让我的脚本执行如下操作:

    cd /somewhere
    git pull
    npm run build
    make deploy
    

    谷歌上的每一个地方我都能看到: os.system("xxx") subprocess.call(...) .

    在bash中,上面的内容很简单,但是我想创建一个cli python应用程序 为我创造所有的东西。

    2 回复  |  直到 6 年前
        1
  •  0
  •   attdona    6 年前

    本着不要重新发明轮子的精神,有很多方法可以用Python自动化构建,获得诸如依赖性管理之类的免费功能。

    一个有用的工具是 doit .

    为了得到一个想法,这是一个非常简单的例子,类似于您的用例:

    import os
    
    MY_PRJ_ROOT='/home/myname/my_project_dir'
    
    def task_cd():
        def cd_to_somewhere():
            os.chdir(MY_PRJ_ROOT)
        return {
            'actions': [cd_to_somewhere]
        }
    
    def task_git_pull():
        """pull my git repo"""
        return {
            'actions': ['git pull'],
        }
    
    def task_build_rust_app():
        """build by awesome rust app"""
        return {
            'actions': ['cargo build']
        }
    

    假设上面是一个名为 dodo.py ,doit任务的默认名称,运行方式为:

    > doit
    

    其他资源

    同样值得注意的是(据我所知,它们不是蟒蛇自动化工具的详尽列表):

    SCons - a software construction tool

    ShutIt - A versatile automation framework

        2
  •  0
  •   Giacomo Catenazzi    6 年前

    os.system 调用shell并将命令发送到shell,这样您就可以轻松地执行以下操作:

    import os
    
    cmd == """\
    cd /somewhere
    git pull
    npm run build
    make deploy
    """"
    
    os.system(cmd)
    

    这太容易了。我们往往会忘记 OS-系统 不要直接执行命令,而是将命令分派给shell。所以我们可以使用重定向和管道。