在shell 脚本里嵌入python

#!/bin/bash
function pytest() {
python - $@ <<EOT
import sys,datetime
print 'Current Time is %s' % datetime.datetime.now()
print sys.argv
EOT
}


RT=$(pytest $@)
echo my python script says: $RT

Share

snmp via python [IF-MIB]

依赖 pysnmp pysnmp-mibs

# -*- coding: utf-8 -*-
'''
Created on 14/11/20.
@author: seven
'''

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
    cmdgen.CommunityData('community_str'),
    cmdgen.UdpTransportTarget(('211.xx.169.xx', 161)),
    cmdgen.MibVariable('IF-MIB', 'ifNumber'),
    cmdgen.MibVariable('IF-MIB', 'ifDescr'),
    cmdgen.MibVariable('IF-MIB', 'ifType'),
    cmdgen.MibVariable('IF-MIB', 'ifMtu'),
    cmdgen.MibVariable('IF-MIB', 'ifSpeed'),
    cmdgen.MibVariable('IF-MIB', 'ifPhysAddress'),

    lookupValues=True
)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'
        )
        )
    else:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
Share

Whoosh 开始

Whoosh is a fast, featureful full-text indexing and searching library implemented in pure Python.

whoosh 是一个纯python实现的快速,多功能的全文索引和搜索库。

Programmers can use it to easily add search functionality to their applications and websites.

程序员可以轻松的给应用和网站添加搜索功能。

Every part of how Whoosh works can be extended or replaced to meet your needs exactly.

whoosh的每个部分都可以扩展或者替换以迎合你的需求。

Some of Whoosh’s features include:

  • Pythonic API.
  • Pure-Python. No compilation or binary packages needed, no mysterious crashes.
  • Fielded indexing and search.
  • Fast indexing and retrieval — faster than any other pure-Python search solution I know of.
  • Pluggable scoring algorithm (including BM25F), text analysis, storage, posting format, etc.
  • Powerful query language.
  • Production-quality pure Python spell-checker (as far as I know, the only one).

whoosh的一些功能包括:

  • python化的API.
  • 纯Python. 不需要编译或者二进制包,没有神秘的崩溃.
  • 派出索引和搜索
  • 快速索引和取回 — 比我知道的任何一个纯python搜索方案都快
  • 可插拔的评分算法 (包括 BM25F), 文本分析, 存储, 发帖格式, 等.
  • 强大的查询语句.
  • 产品级的纯python拼写检查 (我所知的最快的,没有之一).

 

 

Share

Python timelib

可以通过pip安装这个库

 

我是为了要使用和php中的 strtotime函数才用到的,很实用

获取上周的时间戳


from timelib import strtotime
from datetime import date
if __name__=='__main__':
 print date.fromtimestamp(strtotime('-2 week Monday'))

Share

用Make 编译Python项目

python编译后性能并不会提升,但是1来可以减少文件量,2来可以对明文的代码封装,还是挺好的。

makefile

#编译后文件的去处

BINDIR := ../bin

#源代码所在目录
BASEDIR := ../src

#编译参数 可选
DBGFLAGS ?= -O

ifeq ($(findstring -O,$(DBGFLAGS)),-O)
COM := .pyo
else
COM := .pyc
endif

define dirflow
FILES := $(wildcard $(1)*)
DIRS :=
$$(foreach e, $$(FILES), $$(if $$(wildcard $$(e)/*), $$(eval DIRS := $$(DIRS) $$(e))))
FILES := $$(filter-out $$(DIRS),$$(FILES))
ALLFILES := $$(ALLFILES) $$(FILES)
$$(foreach e,$$(DIRS),$$(eval $$(call dirflow,$$(e)/)))
endef

$(eval $(call dirflow ,$(BASEDIR)))
sources := $(filter %.py,$(ALLFILES))
clean_com := $(patsubst %.py, _clean_%.py, $(sources))

MKDIR := mkdir -p
TEST  := test -d
RM    := rm -rf

.PHONY : all

all:$(sources)

%.py:bin_dir
@echo Go into $(dir $@)
$(shell $(TEST) $(subst $(BASEDIR),$(BINDIR),$(dir $@)) || $(MKDIR) $(subst $(BASEDIR),$(BINDIR),$(dir $@)))
python $(DBGFLAGS) -m py_compile $@
mv $(patsubst %.py, %$(COM), $@) $(subst $(BASEDIR),$(BINDIR),$(dir $@))
@echo Compile $@ done.

bin_dir:
$(shell $(TEST) $(BINDIR) || $(MKDIR) $(BINDIR))

.PHONY: clean
clean: $(clean_com)
$(RM) $(BINDIR)

$(clean_com):bin_dir
$(RM)$(patsubst _clean_%.py, %$(COM), $@)

Share

apache+mod_python+django+pyamf与flash通信(@centos)

装apache & mod_python可以通过yum安装,python是linux自带的。
django可以去官方网站
下载https://www.djangoproject.com/download/
安装https://docs.djangoproject.com/en/dev/intro/install/

目录结构-以我自己的习惯:

#mkdir /data
#cd /data
#django-admin.py startproject myproj
#cd myproj
#django-admin.py startapp amfgateway

好了该建立的项目和应用都建好了现在要配置下。

#vi /data/myproj/urls.py
——————————————————————
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns(”,

url(r’^myproj/’, include(‘myproj.amfgateway.urls’)),
)
——————————————————————

#vi /data/myproj/amfgateway/urls.py
——————————————————————

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns(‘amfgateway.views’,
url(r’amfgateway/$’, ‘echoGateway’),
)

——————————————————————

#vi /data/myproj/amfgateway/view.py
——————————————————————
# Create your views here.

from pyamf.remoting.gateway.django import DjangoGateway

def echo(request, data):
return data

services = {
‘echo’: echo
# could include other functions as well
}

echoGateway = DjangoGateway(services)

——————————————————————

随后,配置apache

#vi /etc/httpd/conf/httpd.conf

在文件最后添加
——————————————————————
NameVirtualHost *:80


DocumentRoot /www
ErrorLog logs/error_log
CustomLog logs/access_log common


SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE myproj.settings
PythonDebug On
PythonPath “[‘/data’, ‘/data/myproj’] + sys.path”


——————————————————————

最后
写个as试试链接下

Main.as
——————————————————————
package
{
import flash.net.Responder;
import flash.net.NetConnection;
import flash.display.Sprite;

public class Main extends Sprite
{
// Gateway connection object
private var gateway:NetConnection;

public function Main()
{
// Setup connection
gateway = new NetConnection();

// Connect to gateway
gateway.connect( “http://192.168.1.250/myproj/amfgateway/” );

// This var holds the data we want to pass to the remote service.
var param:String = “Hello World!\n”;

// Set responder property to the object and methods that will receive the
// result or fault condition that the service returns.
var responder:Responder = new Responder( onResult, onFault );

// Call remote service to fetch data
trace(“Start call”);
gateway.call( “echo”, responder, param );
}

// Result handler method
private function onResult( result:Object ): void {
trace( result +”\n”);// prints “Hello World!”
}
// Fault handler method displays error message
private function onFault( error:Object ): void {
// Notify the user of the problem

// status_txt.text = “Remoting error: \n”;
for (var d:String in error) {
trace( error[d] + “\n” );
}
}
}
}

——————————————————————

Share