简体   繁体   English

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

[英]How to pass an escape slash to subprocess.run

Trying to run command this from a Python script:尝试从 Python 脚本运行命令:

gh api "/search/code?q=somecode" --jq ".items[] | { "file": .path, "repo": .repository[\"full_name\"] } "

by way of:通过:

output = subprocess.run( [ 'gh', f'api "/search/code?q={CODE}"', '--jq ".items[] | {{ "file": .path, "repo": .repository[{}] }} "'.format('\\"full_name\\"') ])

to no avail.无济于事。

I've also tried:我也试过:

.format(r'\"full_name\"')

which, afaik, is supposed to work, but I get afaik,应该可以工作,但我明白了

Command '['gh', 'api "/search/code?q=somecode"', '--jq ".items[] | { "file": .path, "repo": .repository[\\"full_name\\"] } "']' returned non-zero exit status 1.

Using .format(repr('\"full_name\"')) yields:使用.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.

Thanks in advance, I've spent at least 3 hours reading docs, SO and asking friends在此先感谢,我已经花了至少 3 个小时阅读文档,所以问朋友

I have likewise attempted this on my Mac OS X (M1 chip) and ran into a similar issue on my end.我同样在我的 Mac OS X(M1 芯片)上尝试过这个并在我这边遇到了类似的问题。 I had originally installed the GitHub CLI ( gh ) via homebrew ( brew ).我最初通过自制软件 ( brew ) 安装了GitHub CLI ( gh )。

I have few points I would suggest fixing:我有几点建议修复:

  1. Use shlex.split to (unequivocally) split multi-word arguments into a list of arguments使用shlex.split (明确地)将多词 arguments 拆分为 arguments 的列表
  2. Pass the full path to the command, which you can get by running which gh in a terminal将完整路径传递给命令,您可以通过在终端中运行which gh来获取该命令
  3. Use an rf'' template- or f- string, where the r is for raw string so backslashes \ are automatically escaped使用rf''模板或 f- 字符串,其中r用于原始字符串,因此反斜杠\会自动转义

Putting all this together:把所有这些放在一起:

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 (redacted): 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