传递字符串作为参数添加转义字符

时间:2015-03-27 02:04:13

标签: python string character-encoding subprocess

我正在访问子进程模块以调用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它传递一个字符串..完全转换?

2 个答案:

答案 0 :(得分:4)

使用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 

OR

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

答案 1 :(得分:1)

删除Shell=True,试试这个:

data = '{"data": [{"content": "blabla"}]}'
from subprocess import check_output
check_output(['curl', '-d', data, 'http://service.location.com'])
相关问题