带有引号和变量的 Python 子进程命令
问题描述
我有一个复杂的命令,我想用子进程运行.它包含单引号和双引号,我想插入一些变量.
I have a complicated command that I want to run with subprocess. It contains single and double quotes and I want to drop in some variables.
这是字符串:
gitlab create_merge_request 5 "{} - New merge request - {}" "{source_branch: '{}', target_branch: 'dev', assignee_id: 1}" --json
我想保留新合并请求"部分周围的引号(它包含两个变量和source_branch"变量周围.source_branch"部分中的花括号也会导致问题.
I want to maintain the quotes around the 'New merge request' section (it contains two variables and around the 'source_branch' variable. The curly braces in the 'source_branch' section are also causing problems.
当我像这样格式化字符串时:
When I format the string like this:
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")
解决方案
使用 subprocess,你最好传递一个字符串列表,而不是一个要由 shell 评估的字符串.这样您就不必担心平衡双引号(以及转义可能的可执行值).
With subprocess, you're better off passing a list of strings rather than a string to be evaluated by the shell. This way you don't need to worry about balancing your double quotes (and escaping potentially executable values).
花括号可以从字符串格式中转义 将它们加倍.
The curly braces can be escaped from string formatting by doubling them.
考虑到这两个注意事项,我可能会这样做:
With those two notes in mind, here's what I might do:
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()
方法
I'm using Python 3.6's f-strings here, but it could also be done with the str.format()
method
"{} - New merge request - {}".format(committerUser, reviewerUser),
"{{source_branch: '{}', target_branch: 'dev', assignee_id: 1}}".format(branchName),
或通过连接显式地连接,这可能比试图记住双花括号的用途更具可读性.
Or explicitly by concatenation, which might be more readable than trying to remember what the double curly braces are for.
committerUser + " - New merge request - " + reviewerUser,
"{source_branch: '" + branchName + "', target_branch: 'dev', assignee_id: 1}",
相关文章