我正在访问子流程模块以调用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]-->nn<head>n <title>Location.comxe2x84xa2 | 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">nn <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)
删除Shell=True
,尝试以下操作:
data = '{"data": [{"content": "blabla"}]}'
from subprocess import check_output
check_output(['curl', '-d', data, 'http://service.location.com'])