7月 08

python mongodb 变量做集合(collection)名

【2011-7-8 张子萌】
当前需求:1)将某个目录下的html文件插入到mongo数据库中。
2)cellection名为html页的上级目录名。
3)document为文件名、html内容

测试目录位置/home/test

#!/usr/bin/python
#-*- coding:utf-8 -*-
import re
import os
import pymongo

find_file=re.compile(r”.html$”)
find_path=r”/home/test”
find_walk=os.walk(find_path)
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
for path,dirs,files in find_walk:
for file in files:
if find_file.search(file):
collection_name=path.split(“/”)[2]
get_html=open(path+”/”+file,’r’)
exec(‘db.’+collection_name+’.save({“file_name”:file,”context”:get_html.read()})’)
get_html.close()

遇到一个问题,好像collection如只是数字(int)插入有问题,所以如果用数字名做collection名可以在前面加个字母。

3月 23

脚本放入crontab不能运行

【整理:张子萌】

linux下编写shell脚本,手动运行正常,但是放到crontab中,就不能正常运行了,这是环境变量的问题。即使使用同一个账户,手动登陆和crontab自动运行所加载的环境变量也是不同的。

有两种方法可以解决:

1. 比较简单,应该在shell编写时就注意。

在shell脚本的头部添加”. $HOME/.bash_profile”(要注意前面有个点,点后面是空格,之后是环境变量位置)。

也可以直接写环境变量的绝对位置。如test用户的根目录在/home/test下可以在shell头部添加”. /home/test/.bash_profile”

2.比较紧急情况,再确认可以手动执行脚本情况下,可以使用另一种方法。使用root权限调用shell脚本。

如果有/home/test/test.sh需要每分钟运行一次,可以使用root登陆,在root的crontab中添加如下:

# crontab -e

*/1 * * * * /home/test/test.sh