我有一个想要与子进程一起运行的复杂命令.它包含单引号和双引号,我想添加一些变量.
这是字符串:
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")
解决方法:
使用子进程,最好传递一个字符串列表,而不是传递要由外壳程序评估的字符串.这样,您无需担心平衡双引号(以及转义潜在的可执行值).
将花括号加倍可以将其设为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}",