简体   繁体   中英

How to use string variable in subprocess.check_output in python

I want to run a command having args on linux using python

i have wriiten following code:

import subprocess

msg = 'this is commit'
cmdtorun = 'hg commit -m "{}"'.format(msg)

try:
    subprocess.check_output(cmdtorun, shell=True)
    print "commit done"
except subprocess.CalledProcessError:
    print "commit failed

but this is giving me error.

Most likely, your problem is something else entirely. Check what error you actually get. I'm guessing that you're executing hg in the wrong directory (pass in the cwd= keyword argument).

Also, your escaping with '"{}"'.format is incorrect - it fails when msg contains a double quote. You could escape with shlex.quote , but that's error-prone. It's far easier to let subprocess do the escaping:

import subprocess
msg = 'this is commit'
try:
    subprocess.check_output(['hg', 'commit', '-m', msg])
    print("commit done")
except subprocess.CalledProcessError as cpe:
    print("commit failed: %r" % cpe)

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