python 脚本作为Windows服务启动

相关包:http://sourceforge.net/projects/pywin32/
[python]
import win32serviceutil
import win32service
import win32event
import time
class test1(win32serviceutil.ServiceFramework):
_svc_name_ = "test_python"
_svc_display_name_ = "test_python"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#在这里写入启动后的操作
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
#在这里写入关闭服务前的操作
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__==’__main__’:
win32serviceutil.HandleCommandLine(test1)
[/python]

Python 作用域的问题

Python作用域很好理解,主要分清全局作用域和局部作用域两个概念,并理解其区别:

1.全局作用域的变量都可以在局部作用域中被访问,例如:

[python]

a=1

def test() :

print a

[/python]

调用test()函数是可以打印出a的值的。

全局作用域的变量除了数值、元组、字符串外都可以被局部作用域改变,那些所以对数值、元组、字符串这些不可变序列进行重新赋值时,是不产生任何变化的;

[python]
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> str="hello"
>>> li=[1,2,3]
>>> def str_change(data):
data="new data"

>>> str_change(str)
>>> str
‘hello’
>>> def li_change(data):
data[0]=5

>>> li_change(li)
>>> li
[5, 2, 3]
>>>
[/python]
如果想在局部作用域内改变不可变序列的值,可以在局部作用域内对变量加上关键词 global
[python]
a=1
def plus_1():
global a
a=a+1
[/python]
同时可以用globals()函数获取全局变量值,vars()获取全部变量的字典,locals()获取全部局部变量的字典

Python相关包

excel操作http://www.python-excel.org/
连接Mysql数据库http://sourceforge.net/projects/mysql-python/files/mysql-python/
串口通信http://pypi.python.org/pypi/pyserial
ocrhttp://code.google.com/p/pytesser/downloads/detail?name=pytesser_v0.0.1.zip&can=2&q=
PIL http://www.pythonware.com/products/pil/

Python串口通信和连接Mysql数据库

串口通信:
http://pypi.python.org/pypi/pyserial
应用如下(程序有点问题,每次关闭串口再打开会出现乱码现象)
[python]
import serial
from time import sleep
ser = serial.Serial(‘/dev/ttyUSB0’, 2400, timeout=1)
def recv(serial):
data, quit = None, False
while 1:
data =serial.read(1)
if data == ”:
continue
sleep(0.02) # data is this interval will be merged
while 1:
n = serial.inWaiting()
if n > 0:
data = "%s%s" % (data,serial.read(n))
else:
quit = True
break
if quit:
break

return data
while 1:
data =recv(ser)
if data== ‘c’ :
ser.close()
break
ser.write(data)
[/python]
Python连接mysql
链接http://sourceforge.net/projects/mysql-python/files/mysql-python/
我没有按照这种方法,因为没安装成功,我用的debian系统,采取包的安装方法
apt-get install python-mysqldb