gpt4 book ai didi

带引号和变量的 Python Subprocess 命令

转载 作者:行者123 更新时间:2023-12-01 03:02:46 25 4
gpt4 key购买 nike

我有一个复杂的命令,我想用子进程运行。它包含单引号和双引号,我想添加一些变量。

这是字符串:

gitlab create_merge_request 5 "{} - New merge request - {}" "{source_branch: '{}', target_branch: 'dev', assignee_id: 1}"  --json

我想保留“新合并请求”部分周围的引号(它包含两个变量和“source_branch”变量周围的引号。“source_branch”部分中的花括号也会引起问题。

当我像这样格式化字符串时:

gitLabCreateMerge = ('/usr/local/bin/gitlab create_merge_request 5 ', str(committerUser), ' requested - Automated Merge Request- ', str(reviewerUser), "'{source_branch:", str(branchName), " target_branch: 'dev', assignee_id: 1}' --json")

看起来像这样:

('/usr/local/bin/gitlab create_merge_request 5 ', 'alice', ' requested - Automated merge request - joe ', "'{source_branch:", 'testdevbranch', " target_branch: 'dev', assignee_id: 1}' --json")

最佳答案

对于子进程,您最好传递字符串列表而不是由 shell 计算的字符串。这样您就不必担心平衡双引号(并转义潜在的可执行值)。

花括号可以是 escaped from string formatting将它们加倍。

考虑到这两个注释,我可能会这样做:

committerUser = 'alice'
reviewerUser = 'joe'
branchName = 'testdevbranch'
cmd = ["gitlab",
"create_merge_request",
"5",
f"{committerUser} - New merge request - {reviewerUser}",
f"{{source_branch: '{branchName}', target_branch: 'dev', assignee_id: 1}}",
"--json"]
subprocess.Popen(cmd, …)

我正在使用Python 3.6的f-strings在这里,但也可以使用 str.format() 方法

"{} - New merge request - {}".format(committerUser, reviewerUser),
"{{source_branch: '{}', target_branch: 'dev', assignee_id: 1}}".format(branchName),

或者明确地通过串联,这可能比尝试记住双花括号的用途更具可读性。

committerUser + " - New merge request - " + reviewerUser,
"{source_branch: '" + branchName + "', target_branch: 'dev', assignee_id: 1}",

关于带引号和变量的 Python Subprocess 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com