使用python中的子进程在linux终端上执行命令

时间:2014-06-16 09:50:53

标签: linux python-2.7 mercurial

我想使用python脚本在linux终端上执行以下命令

hg log -r "((last(tag())):(first(last(tag(),2))))" work

此命令在最近两个影响文件的标签之间提供变更集" work"目录

我试过了:

import subprocess
releaseNotesFile = 'diff.txt'
with open(releaseNotesFile, 'w') as f:
    f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work']))

错误:

abort: unknown revision '((last(tag())):(first(last(tag(),2))))'!
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work']))
TypeError: expected a character buffer object

使用os.popen()

with open(releaseNotesFile, 'w') as file:
    f = os.popen('hg log -r "((last(tag())):(first(last(tag(),2))))" work')
    file.write(f.read())

如何使用子进程执行该命令?

1 个答案:

答案 0 :(得分:2)

要解决您的问题,请将f.write(subprocess...行更改为:

f.write(subprocess.call(['hg', 'log', '-r', '((last(tag())):(first(last(tag(),2))))', 'dcpp']))

解释

从命令行(如bash)调用程序时,将“忽略”"个字符。以下两个命令是等效的:

hg log -r something
hg "log" "-r" "something"

在您的特定情况下,shell中的原始版本必须用双引号括起来,因为它具有括号并且在bash中具有特殊含义。在python中没有必要,因为你用单引号将它们括起来。

相关问题