带引号和变量的 Python Subprocess 命令 [英] Python Subprocess command with quotes and variables

查看:25
本文介绍了带引号和变量的 Python Subprocess 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的命令,我想与子进程一起运行.它包含单引号和双引号,我想放入一些变量.

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")

推荐答案

对于子进程,最好传递字符串列表,而不是要由 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}",

这篇关于带引号和变量的 Python Subprocess 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆