存档

‘python’ 分类的存档

apache mod_python psp

2014年2月20日 评论已被关闭

之前在apache上用python都是通过cgi的方式来调用,这次尝试了一下mod_python模块。

yum安装apache,python,mod_python。
安装过程忽略。
注意python的默认版本,如果有多个版本的话,mod_python还是使用的系统的版本。
阅读全文…

分类: python 标签:

nagios plugins check_proc_runtime

2013年6月3日 评论已被关闭

A nagios plugin of check proc running time. which can check a specified process running time, If it has been running too long time..

code:
check_proc_runtime

usage on nrpe:

$ cat nrpc.conf
command[check_proc_rsync]=/usr/local/nagios/libexec/check_proc_runtime -k rsync -e inotify -c 360

分类: python 标签: , ,

run or spawn in pexpect

2012年8月10日 评论已被关闭

Pexpect is a Python module for spawning child applications and controlling
them automatically. Pexpect can be used for automating interactive applications
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different servers. It
can be used for automated software testing. Pexpect is in the spirit of Don
Libes’ Expect, but Pexpect is pure Python. Other Expect-like modules for Python
require TCL and Expect or require C extensions to be compiled. Pexpect does not
use C, Expect, or TCL extensions. It should work on any platform that supports
the standard Python pty module. The Pexpect interface focuses on ease of use so
that simple tasks are easy.

There are two main interfaces to Pexpect — the function, run() and the class,
spawn. You can call the run() function to execute a command and return the
output. This is a handy replacement for os.system().
I was failed when using spawn() to get output of remote ssh command,

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei_spawn.py

import pexpect
if __name__ == ‘__main__’:

child = pexpect.spawn(‘ssh -oStrictHostKeyChecking=no myname@host.example.com’)
child.expect (‘Password:’)
child.sendline (mypassword)
child.expect (‘$’)
child.sendline (‘hostname’)
print child.before
print child.after

Function run() worked for me,that’s great!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei.py

from pexpect import *

if __name__ == ‘__main__’:

User = ‘myuser’
Host = ‘www.2hei.net’
Pwd = ‘mypwd’
print run (“ssh -oStrictHostKeyChecking=no ” +User+”@”+Host+” ‘hostname;uptime'”, events={‘(?i)password’:Pwd+’\n’})

分类: python 标签:

pexpect Timeout exceeded in read_nonblocking()

2011年10月24日 评论已被关闭

gg resolve from bbs:
vi /usr/lib/python2.6/site-packages/pxssh.py
#add line 134,135:
    123     def synch_original_prompt (self):
    124
    125         “””This attempts to find the prompt. Basically, press enter and record
    126         the response; press enter again and record the response; if the two
    127         responses are similar then assume we are at the original prompt. “””
    128
    129         # All of these timing pace values are magic.
    130         # I came up with these based on what seemed reliable for
    131         # connecting to a heavily loaded machine I have.
    132         # If latency is worse than these values then this will fail.
    133
    134         self.sendline()
    135         time.sleep(0.5)

    136         self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
    137         time.sleep(0.1)

we just put something there before ssh expect read.

分类: python 标签:

useful python modules zz

2011年2月12日 评论已被关闭

mark zz from http://bbs.chinaunix.net/viewthread.php?tid=1855562 :
Graphical interface wxPython http://wxpython.org   
Graphical interface pyGtk http://www.pygtk.org   
Graphical interface pyQT http://www.riverbankcomputing.co.uk/pyqt/   
Graphical interface Pmw http://pmw.sourceforge.net/   
Graphical interface Tkinter 3000 http://effbot.org/zone/wck.htm   
Graphical interface Tix http://tix.sourceforge.net/   
        
Database MySQLdb http://sourceforge.net/projects/mysql-python   
Database PyGreSQL http://www.pygresql.org/   
Database Gadfly http://gadfly.sourceforge.net/   
Database SQLAlchemy http://www.sqlalchemy.org/   
Database psycopg http://www.initd.org/pub/software/psycopg/   
Database kinterbasdb http://kinterbasdb.sourceforge.net/   
Database cx_Oracle http://www.cxtools.net/default.aspx?nav=downloads   
Database pySQLite http://initd.org/tracker/pysqlite   
        
MSN Messenger msnlib http://auriga.wearlab.de/~alb/msnlib/   
MSN Messenger pymsn http://telepathy.freedesktop.org/wiki/Pymsn   
MSN Messenger msnp http://msnp.sourceforge.net/   
Network Twisted http://twistedmatrix.com/   
Images PIL http://www.pythonware.com/products/pil/   
Images gdmodule http://newcenturycomputers.net/projects/gdmodule.html   
Images VideoCapture http://videocapture.sourceforge.net/   
        
Sciences and Maths scipy http://www.scipy.org/   
Sciences and Maths NumPy http://numpy.scipy.org//   
Sciences and Maths numarray http://www.stsci.edu/resources/software_hardware/numarray   
Sciences and Maths matplotlib http://matplotlib.sourceforge.net/   
        
Games Pygame http://www.pygame.org/news.html   
Games Pyglet http://www.pyglet.org/   
Games PySoy http://www.pysoy.org/   
Games pyOpenGL http://pyopengl.sourceforge.net/   
        
Jabber jabberpy http://jabberpy.sourceforge.net/   
        
Web scrape http://zesty.ca/python/scrape.html   
Web Beautiful Soup http://crummy.com/software/BeautifulSoup   
Web pythonweb http://www.pythonweb.org/   
Web mechanize http://wwwsearch.sourceforge.net/mechanize/   
        
Localisation geoname.py http://www.zindep.com/blog-zindep/Geoname-python/   
        
Serial port pySerial http://pyserial.sourceforge.net/   
Serial port USPP http://ibarona.googlepages.com/uspp   
        
Parallel Port pyParallel http://pyserial.sourceforge.net/pyparallel.html   
        
USB Port pyUSB http://bleyer.org/pyusb/   
        
Windows ctypes http://starship.python.net/crew/theller/ctypes/   
Windows pywin32 http://sourceforge.net/projects/pywin32/   
Windows pywinauto http://www.openqa.org/pywinauto/   
Windows pyrtf http://pyrtf.sourceforge.net/   
Windows wmi http://timgolden.me.uk/python/wmi.html   
        
PDA/GSM/Mobiles pymo http://www.awaretek.com/pymo.html   
PDA/GSM/Mobiles pyS60 http://sourceforge.net/projects/pys60   
        
Sound pySoundic http://pysonic.sourceforge.net/   
Sound pyMedia http://pymedia.org/   
Sound FMOD http://www.fmod.org/   
Sound pyMIDI http://www.cs.unc.edu/Research/assist/developer.shtml   
        
GMail libgmail http://libgmail.sourceforge.net/   
Google pyGoogle http://pygoogle.sourceforge.net/   
Expect pyExpect http://pexpect.sourceforge.net/   
WordNet pyWordNet http://osteele.com/projects/pywordnet/   
Command line cmd http://blog.doughellmann.com/2008/05/pymotw-cmd.html   
Compiler backend llvm-py http://mdevan.nfshost.com/llvm-py/   
3D VPython http://vpython.org

分类: python 标签:

compile pyhton2.7 with zlib

2011年1月14日 评论已被关闭
ensure you have installed zlib on your OS.
[2hei.net]# rpm -qa|grep zlib
zlib-1.2.3-3
zlib-devel-1.2.3-3
use source code to compile python2.7:
./configure –enable-shared && make && make install
If you still have this issue:
python: error while loading shared libraries: libpython2.7.so.1.0: cannot open shared object file
solved:
vim /etc/ld.so.conf.d/python2.7.conf
/usr/local/lib
ldconfig
test:
[2hei.net]# python
Python 2.7.1 (r271:86832, Jan 14 2011, 01:34:20) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> imort
KeyboardInterrupt
>>> import sys
>>> sys.modules
{‘copy_reg’: <module ‘copy_reg’ from ‘/usr/local/lib/python2.7/copy_reg.pyc’>, ‘sre_compile’: <module ‘sre_compile’ from ‘/usr/local/lib/python2.7/sre_compile.pyc’>, ‘_sre’: <module ‘_sre’ (built-in)>, ‘encodings’: <module ‘encodings’ from ‘/usr/local/lib/python2.7/encodings/__init__.pyc’>, ‘site’: <module ‘site’ from ‘/usr/local/lib/python2.7/site.pyc’>, ‘__builtin__’: <module ‘__builtin__’ (built-in)>, ‘sysconfig’: <module ‘sysconfig’ from ‘/usr/local/lib/python2.7/sysconfig.pyc’>, ‘__main__’: <module ‘__main__’ (built-in)>, ‘encodings.encodings’: None, ‘abc’: <module ‘abc’ from ‘/usr/local/lib/python2.7/abc.pyc’>, ‘posixpath’: <module ‘posixpath’ from ‘/usr/local/lib/python2.7/posixpath.pyc’>, ‘_weakrefset’: <module ‘_weakrefset’ from ‘/usr/local/lib/python2.7/_weakrefset.pyc’>, ‘errno’: <module ‘errno’ (built-in)>, ‘encodings.codecs’: None, ‘sre_constants’: <module ‘sre_constants’ from ‘/usr/local/lib/python2.7/sre_constants.pyc’>, ‘re’: <module ‘re’ from ‘/usr/local/lib/python2.7/re.pyc’>, ‘_abcoll’: <module ‘_abcoll’ from ‘/usr/local/lib/python2.7/_abcoll.pyc’>, ‘types’: <module ‘types’ from ‘/usr/local/lib/python2.7/types.pyc’>, ‘_codecs’: <module ‘_codecs’ (built-in)>, ‘_warnings’: <module ‘_warnings’ (built-in)>, ‘genericpath’: <module ‘genericpath’ from ‘/usr/local/lib/python2.7/genericpath.pyc’>, ‘stat’: <module ‘stat’ from ‘/usr/local/lib/python2.7/stat.pyc’>, ‘zipimport’: <module ‘zipimport’ (built-in)>, ‘encodings.__builtin__’: None, ‘warnings’: <module ‘warnings’ from ‘/usr/local/lib/python2.7/warnings.pyc’>, ‘UserDict’: <module ‘UserDict’ from ‘/usr/local/lib/python2.7/UserDict.pyc’>, ‘encodings.utf_8’: <module ‘encodings.utf_8’ from ‘/usr/local/lib/python2.7/encodings/utf_8.pyc’>, ‘sys’: <module ‘sys’ (built-in)>, ‘codecs’: <module ‘codecs’ from ‘/usr/local/lib/python2.7/codecs.pyc’>, ‘os.path’: <module ‘posixpath’ from ‘/usr/local/lib/python2.7/posixpath.pyc’>, ‘signal’: <module ‘signal’ (built-in)>, ‘linecache’: <module ‘linecache’ from ‘/usr/local/lib/python2.7/linecache.pyc’>, ‘posix’: <module ‘posix’ (built-in)>, ‘encodings.aliases’: <module ‘encodings.aliases’ from ‘/usr/local/lib/python2.7/encodings/aliases.pyc’>, ‘exceptions’: <module ‘exceptions’ (built-in)>, ‘sre_parse’: <module ‘sre_parse’ from ‘/usr/local/lib/python2.7/sre_parse.pyc’>, ‘os’: <module ‘os’ from ‘/usr/local/lib/python2.7/os.pyc’>, ‘_weakref’: <module ‘_weakref’ (built-in)>}
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
分类: python 标签: ,

DJANGO FORMS:This field is required

2010年12月27日 评论已被关闭

when meet This field is required at django forms, we can add “required=False” at Fields.

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

分类: python 标签:

write nagios nrpe plugin

2010年7月1日 1 条评论

Scripts and executables must do two things (at a minimum) in order to function as Nagios plugins:
1.Exit with one of several possible return values
2.Return at least one line of text output to STDOUT

Plugin Return Code Service State Host State
0 OK UP
1 WARNING UP or DOWN/UNREACHABLE*
2 CRITICAL DOWN/UNREACHABLE
3 UNKNOWN DOWN/UNREACHABLE
Note: If the use_aggressive_host_checking option is enabled, return codes of 1 will result in a host
state of DOWN or UNREACHABLE. Otherwise return codes of 1 will result in a host state of UP.

Plugin Output Spec
At a minimum, plugins should return at least one of text output. Beginning with Nagios 3, plugins can
optionally return multiple lines of output. Plugins may also return optional performance data that can
be processed by external applications. The basic format for plugin output is shown below:
TEXT OUTPUT | OPTIONAL PERFDATA
LONG TEXT LINE 1
LONG TEXT LINE 2

LONG TEXT LINE N | PERFDATA LINE 2
PERFDATA LINE 3

PERFDATA LINE N

this is my python scripts:
#!/usr/bin/evn python
# -*- coding: utf-8 -*-

import sys,getopt
import memcache

memcached_host=’2hei.net’
memcached_port=11211
Warning_item=120
Critical_item=20

def usage():
    print “””
Usage: check_memcached [-h|–help] [-w|–warning curr_items] [-c|–critical curr_items]”
Warning curr_items defaults to 120
Critical curr_items defaults to 20
“””
    sys.exit(3)

#get curr_items from memcache stats
def get_memcache_curr_items(mc):
    #mc = memcache.Client([memcached_host+’:’+str(memcached_port)], debug=0)
    stats = mc.get_stats()[0][1]   
    #for i in xrange(0,100):
    #    mc.set(‘key’+str(i),’value’+str(i))
    #for k,v in stats.items():
    #    print k,v
    items = stats.get(‘curr_items’)
    return items

if __name__ == “__main__”:
    warning_item = 0
    critical_item = 0

    try:
        options, args = getopt.getopt(sys.argv[1:],”h:w:c:”,”–help –warning= –critical=”,)
    except getopt.GetoptError:
        usage()
        sys.exit(3)

    try:
        mc = memcache.Client([memcached_host+’:’+str(memcached_port)], debug=0)
        items = get_memcache_curr_items(mc)
        mc.disconnect_all()
    except Exception:
        print “Cannot get memcache’s curr_items.”,Exception
        sys.exit(3)

    for name, value in options:
        if name in (“-h”, “–help”):
            usage()
            sys.exit(3)
        if name in (“-w”, “–warning”):
            warning_item = value
        if name in (“-c”, “–critical”):
            critical_item = value

    if warning_item == 0:
        warning_item = Warning_item
    if critical_item == 0:
        critical_item = Critical_item

    if int(items) <= int(critical_item):
        print ‘MEMCACHED_ITEM CRITICAL: curr_items is:’,items
        sys.exit(2)
    if int(items) <= int(warning_item):
        print ‘MEMCACHED_ITEM WARNING: curr_items is:’,items
        sys.exit(1)
    else:
        print ‘MEMCACHED_ITEM OK: curr_items is:’,items
        sys.exit(0)

when encounter errors:
CHECK_NRPE: No output returned from daemon.
or
CHECK_NRPE: Received 0 bytes from daemon.  Check the remote server logs for error messages.
this shows your plugins return output is null

分类: OpenSource, python 标签:

write a own tools of WorldTime with pytz

2010年6月29日 评论已被关闭

require : python2.6 pytz

#!/usr/bin/env python
# -*- coding: gbk -*-
from datetime import datetime, timedelta
from time import gmtime, strftime
from pytz import timezone
import pytz, time,os

#def convert_datetime(unix_timestamp=1143408000, tz=1, long_fmt=1):
def convert_datetime(dt=’2007-01-01 00:00:00′, tz=”, dest_fmt=”, time_stamp=0):
    fmt      = ‘%Y-%m-%d %H:%M:%S’
    if time_stamp == 0:
        dt_stamp = time.mktime(time.strptime(dt, fmt))
    else:
        dt_stamp = float(dt)
    utc      = pytz.utc
    utc_dt   = datetime.utcfromtimestamp(dt_stamp).replace(tzinfo=utc)  
    dest_tz  = timezone(tz)
    dest_dt  = dest_tz.normalize(utc_dt.astimezone(dest_tz))  
    return dest_dt.strftime(dest_fmt)

#define all citys here
citys = {‘Asia/Shanghai’:’Asia/Shanghai 上 海’,
        ‘America/Los_Angeles’:’America/Los_Angeles 旧金山’,
        ‘Etc/GMT’:’Etc/GMT 格林威治标准时间’,
        ‘US/Pacific’:’US/Pacific PT 太平洋时间’,
        ‘UTC’:’UTC 世界标准时间’,
        #’Etc/GMT+8′:’Etc/GMT+8′,
       }
 
if __name__ == ‘__main__’:
    while True:
        os.system(‘cls’)
        print ‘————–时间对照————–‘
        for k,v in citys.items():
            print convert_datetime(dt=strftime(“%Y-%m-%d %H:%M:%S”, time.localtime()), tz=k,dest_fmt=’%Y-%m-%d %H:%M:%S’),’\t[‘+v+’]’
        print ‘————————————‘
        time.sleep(1)

       
run.bat
set path=D:\python26\;%path%
D:
cd D:\Profiles\2hei.net\eclipse-project\py\myapp\src\time_format
python world_time.py

running like this:

world_time_zone.png

 

分类: python 标签:

python解析xml的字符集问题的处理

2010年5月7日 3 条评论

python版本:2.6

案例一: test.xml
<?xml version=”1.0″ encoding=”utf8″?>
调用:
xmldoc = minidom.parse(test.xml)
报错:
Traceback (most recent call last):
  File “D:\project\src\myapp\src\xml\testdomxml.py”, line 14, in <module>
    xmldoc = minidom.parse(response)
  File “D:\Python\lib\xml\dom\minidom.py”, line 1918, in parse
    return expatbuilder.parse(file)
  File “D:\Python\lib\xml\dom\expatbuilder.py”, line 928, in parse
    result = builder.parseFile(file)
  File “D:\Python\lib\xml\dom\expatbuilder.py”, line 207, in parseFile
    parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unknown encoding: line 1, column 30

修改后:test2.xml
<?xml version=”1.0″ encoding=”utf-8″?>
再次调用
xmldoc = minidom.parse(test2.xml)
没有问题了。 囧一个!

详细可见python bug 列表: http://bugs.python.org/msg63471

案例二:
xmldoc = minidom.parse(urllib.urlopen(‘http://rss.sina.com.cn/news/marquee/ddt.xml’))
正常调用

xmldoc = minidom.parse(urllib.urlopen(‘http://news.163.com/special/00011K6L/rss_newstop.xml”))
报错:
  File “D:\Python\lib\xml\dom\expatbuilder.py”, line 207, in parseFile
    parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unknown encoding: line 1, column 30

观察sina和163的两个rss源文件看,并未发现特别的异常,不过将163的保存为文件rssnew163.xml,在其头部添加
<?xml version=”1.0″ encoding=”utf-8″?>
然后再调用
xmldoc = minidom.parse(“rssnew163.xml”)
问题解决,看来还是字符编码的问题了。
对于使用urllib实时更新rss的就需要预先处理一下了,先保存rss文件,然后添加上述行,或者将xml文件转换成utf-8编码即可。

分类: python 标签: ,