简体   繁体   English

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

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

I want to execute following command on linux terminal using python script 我想使用python脚本在linux终端上执行以下命令

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

This command give changesets between last two tags who have affected files in "work" directory 此命令提供了影响“工作”目录中文件的最后两个标签之间的变更集

I tried: 我试过了:

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']))

error: 错误:

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

Working with os.popen() 使用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())

How to execute that command using subprocess ? 如何使用子进程执行该命令?

To solve your problem, change the f.write(subprocess... line to: 要解决您的问题,请将f.write(subprocess...行更改为:

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

Explanation 说明

When calling a program from a command line (like bash), will "ignore" the " characters. The two commands below are equivalent: 从命令行(如bash)调用程序时,将“忽略"字符。以下两个命令等效:

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

In your specific case, the original version in the shell has to be enclosed in double quotes because it has parenthesis and those have a special meaning in bash. 在您的特定情况下,shell中的原始版本必须用双引号引起来,因为它带有括号,并且在bash中具有特殊含义。 In python that is not necessary since you are enclosing them using single quotes. 在python中,这是不必要的,因为您使用单引号将它们括起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM