python - 用 Python 实现的可移植命令执行语法

标签 python shell cross-platform command

在定义一组要运行的命令方面,Python 并不是一种很好的语言。巴什是。但 Bash 并不能在 Windows 上简单地运行。

背景:我正在尝试在 mac/win/linux 上构建一组程序 - 并在它们之间建立依赖关系。类似 macports 的东西,但应该适用于列出的所有三个平台。

这就需要有一种类似 shell 的语言,可以用来定义为构建/修补/等而运行的命令序列......一个特定的程序,例如:

post-destroot {
    xinstall -d ${destroot}${prefix}/share/emacs/${version}/leim
    delete ${destroot}${prefix}/bin/ctags
    delete ${destroot}${prefix}/share/man/man1/ctags.1
    if {[variant_isset carbon]} {
        global version
        delete ${destroot}${prefix}/bin/emacs ${destroot}${prefix}/bin/emacs-${version}
    }
}

以上来自emacs Portfile in macports 。除了指定按顺序执行的简单命令列表之外,请注意变量、条件、函数的使用。

虽然语法不是Python,但实际的执行语义必须使用子进程或其他方式推迟到Python。简而言之,我应该能够“运行”这样的脚本..但是对于每个命令,都会调用一个指定的 Hook 函数,该函数实际上运行作为参数传递的任何命令。我希望你能明白。

最佳答案

听起来您需要 PyParsing 的某种组合和 Python Subprocess .

我发现子进程有点令人困惑,尽管 MOTW关于它,所以我经常使用这种包装器代码。

from subprocess import Popen, PIPE

def shell(args, input=None):
    p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(input=input)
    return stdout, stderr

关于python - 用 Python 实现的可移植命令执行语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1249165/

相关文章:

shell - 在 Windows 7 上使用 scala.sys.process 调用 echo

c++ - 在 VS 2005(8) IDE 中使用 GCC

android - 跨平台推送 API

python - 如何引用在我自己的 sphinx 扩展中生成的自定义索引?

python - 应该在 Django 中编写什么样的测试

python - 使 PRNG 跨软件一致

shell - ulimit -u 的范围是什么?

C - 单 shell 管道实现不断在终端中挂起

shell - Grep Shell 脚本 : How do I Count the Number of Occurrences of Each Substring?

python - 标签绘制的椭圆