
[英]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.