python - 使用 python 中的 ruby​​ gem/命令

标签 python shell command subprocess haml

我已经在我的 Mac 上安装了 Ruby gem 'haml',我可以在终端使用以下命令将 haml 文件编译为 html 文件:

haml 'path/to/haml/file.haml' 'desired/html/path/file.html'

此命令只是在第二个路径中创建一个 html 文件,并且在终端中不提供任何输出。例如,这个命令:

haml "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.haml" "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.html"

在给定路径创建一个sugar.html 文件。现在我正在尝试从 python 脚本使用此功能。当我在 IDLE 的交互式 python shell 中输入以下内容时:

>>>import subprocess
>>>subprocess.Popen('haml "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.haml"        "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.html"', shell=True, executable='/bin/bash')
<subprocess.Popen object at 0x159d6f0>

我得到的输出表明该进程已运行,但是没有输出文件。为什么会发生这种情况?我什至输入了 Shell 参数,但没有显示交互式 shell。另外,我在某处读到,使用的默认 shell 不是 bash,而 Mac 终端使用的是 bash,所以我也将其放入以进行良好的测量。

按照 icktoofay 的建议,我运行了 check_call。这是我收到的回溯:

Traceback (most recent call last):
File "/Users/neil/Desktop/subprocesstest.py", line 7, in p = subprocess.check_call(x, shell=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 504, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command 'haml "/Volumes/Macintosh HD/Users/neil/Sites/ICSP/sugar.haml" "/Volumes/Macintosh HD/Users/neil/Sites/ICSP/sugar.html"' returned non-zero exit status 127

根据bash reference manual ,在搜索要执行的命令时,

If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory containing an executable file by that name. ... If that function is not defined, the shell prints an error message and returns an exit status of 127.

但是,我认为在添加 shell 和可执行参数后确实找到了 haml 命令,因为在此之前,它给出了“文件或目录未找到错误”,这表明该函数不能直接执行,而是仅在 shell 中。

现在如何让 python 找到这个 haml 命令?或者我是否必须使用一些丑陋的解决方法,例如 applescript,然后调用 haml 命令。

最佳答案

我看到您正在使用shell=True,所以我希望一切都能正常工作。使用 Python 2.7.1 和 haml 3.1.1 在本地检查它,执行它没有任何问题。还有一些您可能感兴趣的 python 实现,PyHAML , HamlPy , djamldjango-haml .

import subprocess
subprocess.Popen(['haml', 'hello.haml', 'hello.html'], shell=True)

% cat hello.html
<strong class='code' id='message'>Hello, World!</strong>

关于python - 使用 python 中的 ruby​​ gem/命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239218/

相关文章:

shell - 从 Jenkins 输出中获取数据并绘制/绘制它

command - 显示Vim中间命令

python - 如何在python中实现引用列表?

python - 获取 Qt 中的输出 : 'QProcess::start()' and 'QProcess:readAllStandardOutPut()'

linux - 如何在查找命令中转义 -exec?

linux - 如何等待命令的特定输出字符串并执行另一个命令

python - 过滤(平滑)连续流数据的最有效方法是什么

Python:如何将文本目录读入列表

Grails 数据绑定(bind) - 带有 Maps 的命令对象

wpf - 正确的 MVVM 模式 WPF 命令实现