使用python中的子进程在linux终端上执行命令
我想使用python脚本在linux终端上执行以下命令
I want to execute following command on linux terminal using python script
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
我尝试过:
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()
Working with 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 ?
要解决您的问题,请将f.write(subprocess...
行更改为:
To solve your problem, change the f.write(subprocess...
line to:
f.write(subprocess.call(['hg', 'log', '-r', '((last(tag())):(first(last(tag(),2))))', 'dcpp']))
说明
从命令行(如bash)调用程序时,将忽略" "
字符.以下两个命令是等效的:
Explanation
When calling a program from a command line (like bash), will "ignore" the "
characters. The two commands below are equivalent:
hg log -r something
hg "log" "-r" "something"
在您的特定情况下,shell中的原始版本必须用双引号引起来,因为它带有括号,并且在bash中具有特殊含义.在python中,这是不必要的,因为您使用单引号将它们括起来.
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. In python that is not necessary since you are enclosing them using single quotes.