python - 在双引号内添加变量,变量也包含双引号

python - add Variables inside double quotes, The Variables also contains double quotes

我有原始内容,我需要如下所示的预期输出。

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "Merge dev branch to Master", "source": { "branch": { "name": "Dev" }, "repository": { "full_name": "username/BB_Access" } }, "destination": { "branch": { "name": "master" } }, "close_source_branch": false }'

下面是我试过的代码。

import subprocess
BBrepo = "BB_Access"
BBuser = "username"
src_branch = "Dev"
Dest_branch = "master"
pull_command = "curl -X POST -H "'"Content-Type: application/json"'" https://bitbucket.org/api/2.0/repositories/"+BBuser+"/"+BBrepo+"/pullrequests -d '"'{ "title": "python_pull_request", "source": { "branch": { "name": '"' "+src_branch+" }, '"'repository": { "full_name": '"'"+BBuser+"/"+BBrepo+" } }, '"'destination": { "branch": { "name": '"'"+Dest_branch+'"'" } }, '"'close_source_branch": false }'"'"

print pull_command

但它给出的输出如下

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "python_pull_request", "source": { "branch": { "name": ' Dev }, 'repository": { "full_name": 'username/BB_Access } }, 'destination": { "branch": { "name": 'master" } }, 'close_source_branch": false }'

谁能建议我获得预期输出的更好方法。

我看到两种方式:

  • ''中使用"(或相反)
  • 转义,如"\""'\''

你可以试试这个:

import subprocess
BBrepo = "BB_Access"
BBuser = "username"
src_branch = "Dev"
Dest_branch = "master"
pull_command = 'curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/'+BBuser+'/'+BBrepo+'/pullrequests -d \'{ "title": "python_pull_request", "source": { "branch": { "name": '+'"'+src_branch+'"'+' }, "repository": { "full_name": '+'"'+BBuser+'/'+BBrepo+'"'+' } }, "destination": { "branch": { "name": '+'"'+Dest_branch+'"'+' } }, "close_source_branch": false }\''

print(pull_command)

并得到:

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "python_pull_request", "source": { "branch": { "name": "Dev" }, "repository": { "full_name": "username/BB_Access" } }, "destination": { "branch": { "name": "master" } }, "close_source_branch": false }'