
[英]How do I pass in a list of arguments to subprocess.run?(python)
[英]How to pass an escape slash to subprocess.run
嘗試從 Python 腳本運行命令:
gh api "/search/code?q=somecode" --jq ".items[] | { "file": .path, "repo": .repository[\"full_name\"] } "
通過:
output = subprocess.run( [ 'gh', f'api "/search/code?q={CODE}"', '--jq ".items[] | {{ "file": .path, "repo": .repository[{}] }} "'.format('\\"full_name\\"') ])
無濟於事。
我也試過:
.format(r'\"full_name\"')
afaik,應該可以工作,但我明白了
Command '['gh', 'api "/search/code?q=somecode"', '--jq ".items[] | { "file": .path, "repo": .repository[\\"full_name\\"] } "']' returned non-zero exit status 1.
使用.format(repr('\"full_name\"'))
產生:
Command '['gh', 'api "/search/code?q=staging-procore-tech-docs+org:procore"', '--jq ".items[] | { "file": .path, "repo": .repository[\'"full_name"\'] } "']' returned non-zero exit status 1.
在此先感謝,我已經花了至少 3 個小時閱讀文檔,所以問朋友
我同樣在我的 Mac OS X(M1 芯片)上嘗試過這個並在我這邊遇到了類似的問題。 我最初通過自制軟件 ( brew
) 安裝了GitHub CLI ( gh
)。
我有幾點建議修復:
shlex.split
(明確地)將多詞 arguments 拆分為 arguments 的列表which gh
來獲取該命令rf''
模板或 f- 字符串,其中r
用於原始字符串,因此反斜杠\
會自動轉義把所有這些放在一起:
from __future__ import annotations
import shlex
import subprocess
CODE = 'somecode'
# full path to `gh` command
GH_BINARY = '/opt/homebrew/bin/gh'
cmd: list[str] = shlex.split(rf'{GH_BINARY} api "/search/code?q={CODE}" --jq ".items[] | {{ "file": .path, "repo": .repository[\"full_name\"]}} "')
result = subprocess.run(cmd, capture_output=True)
print('Return Code:', result.returncode)
print('Output:', result.stdout.decode())
Output(編輯):
Return Code: 0
Output: {"file":"tuixiangzi-control/Debug/tuixiangzi-control.Build.CppClean.log","repo":"ChaoFeng-alone/tuixiangzi"}
{"file":"tuixiangzi-easyx/Debug/tuixiangzi-easyx.Build.CppClean.log","repo":"ChaoFeng-alone/tuixiangzi"}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.