我有一个复杂的命令,我想用子进程运行。它包含单引号和双引号,我想删除一些变量。
这是字符串:
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")
答案 0 :(得分:2)
使用子进程,您最好不要传递字符串列表而不是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}",