簡體   English   中英

如何使用 % 運行命令?

[英]How to run a command with %?

我正在嘗試在 python 中運行命令git log origin/master..HEAD --format=format:"%H"如下但遇到以下錯誤,我試圖轉義%但這並不能解決錯誤,任何想法如何解決?

def runCmd2(cmd):
    logger.info("Running command %s"%cmd)
    proc = Popen(cmd ,universal_newlines = True, shell=True, stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    return output.strip(),error.strip()

def get_local_commits():
    """Get local commits """
    branch = "master"
    cmd = "git log origin/%s..HEAD  --format=format:\"%H\" "%(branch)
    output,error = runCmd2(cmd)
    return output,error

錯誤:-

  File "/Users/gnakkala/jitsuin/wifi-ci/enable_signing.py", line 45, in get_local_commits
    cmd = "git log origin/%s..HEAD  --format=format:\"%H\" "%(branch)
TypeError: not enough arguments for format string

要逃避 % 你加倍它,使用 %%

branch = "master"
cmd = 'git log origin/%s..HEAD  --format=format:"%%H"' % branch

你根本不應該這里使用 shell,這使得問題 go 消失了。

def runCmd2(cmd: list[str):
    logger.info("Running command %s"%(' '.join(cmd))
    proc = Popen(cmd, universal_newlines=True, stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    return output.strip(),error.strip()

def get_local_commits():
    """Get local commits """
    branch = "master"
    cmd = ["git", "log", "origin/{}..HEAD".format(branch), '--format=format:%H']
    output,error = runCmd2(cmd)
    return output,error

% 插值已過時

改用 f-strings!

def runCmd2(cmd):
    logger.info(f'Running command {cmd}')
    proc = Popen(cmd ,universal_newlines = True, shell=True, stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    return output.strip(),error.strip()

def get_local_commits():
    """Get local commits """
    branch = "master"
    cmd = f'git log origin/{branch}..HEAD  --format=format:\"{'%H'}\"'
    output,error = runCmd2(cmd)
    return output,error

暫無
暫無

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

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