简体   繁体   中英

Execute command on linux terminal using subprocess in python

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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