![](/img/trans.png)
[英]Using subprocess to execute a linux command in python and then grab the resulting prompt
[英]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.