Execute command on linux terminal using subprocess in python

≡放荡痞女 提交于 2019-12-24 15:32:19

问题


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

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()

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 ?


回答1:


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

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"

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.



来源:https://stackoverflow.com/questions/24240910/execute-command-on-linux-terminal-using-subprocess-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!