我想调用一些函数,但我不知道如何导入包。我尝试过如下但是失败了。我能怎么做? (我想使用一些第三方软件包来分析每个文档,下面的代码只是一个测试)
如果你知道答案,请,请
import couchdb as db
import datetime
couch = db.Server()
d1 = couch['test']
def map(doc):
text = doc['text']
ti = doc['timestamp_ms']
ti = ti[:10] + '.' + ti[10:]
dateArray = datetime.datetime.utcfromtimestamp(float(time))
if (dateArray.time().hour < 12):
yield ["am"], text
else:
yield ["pm"], text
for row in d1.query(map, descending=True, language='python'):
print row.key, row.value
答案 0 :(得分:0)
只有在map函数中导入datetime时,才能在map函数中使用datetime。所以你的例子看起来像 -
def map(doc):
text = doc['text']
ti = doc['timestamp_ms']
ti = ti[:10] + '.' + ti[10:]
from datetime import datetime
dateArray = datetime.utcfromtimestamp(float(time))
if (dateArray.time().hour
However, you cannot load third-party libraries in the map function. I tried importing the nose test library and saw this in couch logs -
[[{initial_call, {couch_os_process,init,['Argument__1']}}, {pid,<0.14643.4>}, {registered_name,[]}, {error_info, {exit, {function_clause, [{couch_os_process,handle_info, [{#Port<0.13927>, {data, {eol, <<"{\"log\": \"Traceback (most recent call last):\n File \\"/usr/local/lib/python2.7/dist-packages/couchdb/view.py\\", line 79, in map_doc\n results.append([[key, value] for key, value in function(doc)])\n File \\"\\", line 5, in map\nImportError: No module named nose\n\"}">>}}}, {os_proc,"couchpy",#Port<0.13927>, #Fun, #Fun,5000}]}, {gen_server,handle_msg,5}, {proc_lib,init_p_do_apply,3}]}, [{gen_server,terminate,6}, {proc_lib,init_p_do_apply,3}]}},
如果您在主机python安装上直接安装第三方库,而不是在虚拟环境中,则可以。但是,我不推荐这种做法。总是使用虚拟环境。