题主,你基本操作没什么问题,有几个小地方要修改一下,修改如下:
你的源码:
PyObject* list = PyList_New(3)
for (size_t i = 0i <3i++)
PyList_Append(list, Py_BuildValue("i", i))
PyEval_CallObject(pFunc, list)
--------------------------------------------------------------------------------------
修改后,应该是这样PyObject* pArgs = NULL
PyObject* list = PyList_New(0) //3改成0
pArgs = PyTuple_New(1) //定义1个参数
for (size_t i = 0 i < 3 i++)
PyList_Append(list, Py_BuildValue("i", i)) //这样才能用Append,
PyTuple_SetItem(pArgs, 0, list) //将列表赋给参数
PyEval_CallObject(pFunc, list) //传入参数,调用函数
注意事项:PyList_New(0) 初始化0的时候,应该用Append初始化
PyList_New(3) 初始化3个时候,应该用SetItem初始化
如果用Append的话,会出现[NULL, NULL, NULL]的情况
我在给一个完整的:
Python :(hello.py)
def TestList(nlist):print(nlist)
return
一般参数都是已元组形式传入的
Py_Initialize()
PyRun_SimpleString("import sys")
PyRun_SimpleString("sys.path.append('./')")
PyObject* pModule =NULL
PyObject* pList = NULL
PyObject* pFunc = NULL
PyObject* pArgs = NULL
pModule = PyImport_ImportModule("hello")
pFunc = PyObject_GetAttrString(pModule, "TestList")
pArgs = PyTuple_New(1)
pList = PyList_New(0)
for (int i = 0 i < 3 i++)
{
PyList_Append(pList, Py_BuildValue("i", i))
}
PyTuple_SetItem(pArgs, 0, pList)
pRet = PyEval_CallObject(pFunc, pArgs)
Py_Finalize()
最后输出的:[0, 1, 2]
1.如果机器上安装了 Python 的 setuptools,可以通过下面的命令来安装 poster:easy_install poster
# test_client.pyfrom poster.encode import multipart_encodefrom poster.streaminghttp import register_openersimport urllib2# 在 urllib2 上注册 http 流处理句柄register_openers()# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码# "image1" 是参数的名字,一般通过 HTML 中的 <input>标签的 name 参数设置# headers 包含必须的 Content-Type 和 Content-Length# datagen 是一个生成器对象,返回编码过后的参数datagen, headers = multipart_encode({"image1": open("DSC0001.jpg", "rb")})# 创建请求对象request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)# 实际执行请求并取得返回print urllib2.urlopen(request).read()
很简单,文件就上传完成了。
2.其中那个 register_openers() 相当于以下操作:
from poster.encode import multipart_encodefrom poster.streaminghttp import StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandlerhandlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandler]opener = urllib2.build_opener(*handlers)urllib2.install_opener(opener)
3.另外,poster 也可以携带 cookie,比如:
opener = poster.streaminghttp.register_openers()opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))params = {'file': open("test.txt", "rb"), 'name': 'upload test'}datagen, headers = poster.encode.multipart_encode(params)request = urllib2.Request(upload_url, datagen, headers)result = urllib2.urlopen(request)