簡體   English   中英

使用python中的子進程在linux終端上執行命令

[英]Execute command on linux terminal using subprocess in python

我想使用python腳本在linux終端上執行以下命令

hg log -r "((last(tag())):(first(last(tag(),2))))" 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())

如何使用子進程執行該命令?

要解決您的問題,請將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中,這是不必要的,因為您使用單引號將它們括起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM