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.
This is the string:
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, …)
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}",