繁体   English   中英

如何将转义斜杠传递给 subprocess.run

[英]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 )。

我有几点建议修复:

  1. 使用shlex.split (明确地)将多词 arguments 拆分为 arguments 的列表
  2. 将完整路径传递给命令,您可以通过在终端中运行which gh来获取该命令
  3. 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM