Skip to main content
 首页 » 编程设计

python之将字符串作为参数传递会添加转义字符

2025年05月04日75telwanggs

我正在访问子进程模块以调用 shell 函数。函数调用的一部分是字符串:

data = '\'{"data": [{"content": "blabla"}]}\'' 

传递字符串时,出现以下错误:

from subprocess import check_output 
check_output(['curl', '-d', data, 'http://service.location.com'], shell=True) 
Error: raise CalledProcessError(retcode, cmd, output=output) ... returned non-zero exit status 2 

我实际上知道问题所在,字符串以它看起来的方式传递给 Python,转义等等。

使用控制台,

$ curl -d \'{"data": [{"content": "blabla"}]}\' http://service.location.com 

给出同样的错误,而

$ curl -d '{"data": [{"content": "blabla"}]}' http://service.location.com 

完美运行。有什么想法可以告诉 Python 它传递的是一个完全转换的字符串吗?

请您参考如下方法:

当您使用 shell=True 参数时,您不需要拆分您的实际命令。

>>> check_output('''curl -d '{"data": [{"content": "blabla"}]}' http://service.location.com''', shell=True) 
b'<!DOCTYPE html>\n<!--[if lt IE 7]>      <html class="location no-js lt-ie9 lt-ie8 lt-ie7" lang="en" ng-app="homeapp" ng-controller="AppCtrl"> <![endif]-->\n<!--[if IE 7]>         <html class="location no-js lt-ie9 lt-ie8" lang="en" ng-app="homeapp" ng-controller="AppCtrl"> <![endif]-->\n<!--[if IE 8]>         <html class="location no-js lt-ie9" lang="en" ng-app="homeapp" ng-controller="AppCtrl"> <![endif]-->\n<!--[if gt IE 8]><!--> <html class="location no-js" ng-app="homeapp" ng-controller="AppCtrl"> <!--<![endif]-->\n\n<head>\n    <title>Location.com\xe2\x84\xa2 | Real Estate Locations for Sale and Rent</title>\n    <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /><![endif]-->\n    <meta charset="utf-8">\n\n                <link rel="dns-prefetch" href="//ajax.googleapis.com" />\n  

>>> data = """'{"data": [{"content": "blabla"}]}'""" 
>>> check_output('''curl -d {0} http://service.location.com'''.format(data), shell=True)