簡體   English   中英

如何在python中的subprocess.check_output中使用字符串變量

[英]How to use string variable in subprocess.check_output in python

我想使用python在linux上運行一個帶有args的命令

我有以下代碼:

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

但這給了我錯誤。

最有可能的是,你的問題完全不同。 檢查你實際得到的錯誤。 我猜你在錯誤的目錄中執行hg (傳入cwd= keyword參數)。

此外,您使用'"{}"'.format轉義是不正確的 - 當msg包含雙引號時它會失敗。 你可以使用shlex.quote逃脫,但這很容易出錯。 讓子進程執行轉義要容易得多:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM