zoukankan      html  css  js  c++  java
  • Python写windows service及exe的安装程序

    一、 在使用python来创建windows服务, 需要使用pywin32类库, 下载地址:http://sourceforge.net/projects/pywin32/

    下面我们创建一个什么也不做的服务,代码如下:
    win32test.py

    import win32serviceutil
    import win32service
    import win32event

    class win32test(win32serviceutil.ServiceFramework):
        _svc_name_ = "Python Win32 Service"
        _svc_display_name_ = "Python Win32 Service"
        _svc_description_ = "Just for a demo, do nothing."
        def __init__(self, args):
            win32serviceutil.ServiceFramework.__init__(self, args)
            self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
           
        def SvcDoRun(self):

        # 把你的程序代码放到这里就OK了  

        # your code here

        # 以下斜体字体表示的方法未验证过       

        command="python test.py"   
            try:  
                Proc=Popen(command,shell=True,stdout=PIPE,stderr=STDOUT)  
                Str=RRDDataProc.stdout.readline()  
            except:  
                Str="error happend"


            win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
           
        def SvcStop(self):
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            win32event.SetEvent(self.hWaitStop)
       
    if __name__=='__main__':
        win32serviceutil.HandleCommandLine(win32test)

    如果你想使用这个服务在启动或者停用时候做点事, 那么就把你要实现的业务写给对应的方法里SvcDoRun和SvcStop.
    其他方法大同小异,比如这里

    -----------------------------------------------------------------------------------

    如果不需要制作安装包,可以

    安装服务    python PythonService.py install

    自动启动    python PythonService.py --startup auto install

    启动服务    python PythonService.py start 

    重启服务    python PythonService.py restart

    停止服务    python PythonService.py stop

    删除/卸载服务  python PythonService.py remove

    --------------------------------------------------------------------------------------
    二、使用py2exe来把我们上面的service创建成安装文件, py2exe下载地址:http://sourceforge.net/projects/py2exe/
    setup.py

    from distutils.core import setup
    import py2exe

    class Target:
        def __init__(self, **kw):
            self.__dict__.update(kw)
            # for the versioninfo resources
            self.version = "1.0.0"
            self.company_name = "Founder Software Suzhou Co. Ltd."
            self.copyright = "Copyright © 2009 Founder Software (Suzhou) Co., Ltd. "
            self.name = "Jchem cartridge windows service"


    myservice = Target(
        description = 'foo',
        modules = ['win32test'],
        cmdline_style='pywin32',
        icon_resources=[(1, "cartrigde.ico")]
    )

    options = {"py2exe":  
                {   "compressed": 1,  
                    "bundle_files": 1
                }  
              } 
             
    setup(
        service=[myservice],
        options = options,
        zipfile = None,
        windows=[{"script": "win32test.py"}],
    )

    三、使用python setup.py py2exe命令来生成安装文件了,要想以后简单些的话写个bat文件,点击这里

    四、生成的安装文件可以使用一下命令来执行控制服务:
    win32test.exe install
    win32test.exe start
    win32test.exe stop
    win32test.exe remove

    或者

    sc  create win32test binPath= E:pythonpydevsrcdistProductCollectWin32ServiceSetup.exe 

    注意上面“=”后面是带空格的

    sc start win32test

    sc delete win32test

    详情请运行 sc --help。

    ---

    1. python打包exe,网上搜的模板,完全够用:

    #----bundle_files有效值----
    #	3 (默认)不打包。
    #	2 打包,但不打包Python解释器。
    #	1 打包,包括Python解释器。
    
    #----zipfile的有效值----
    #	不填	(默认)生成一个library.zip文件
    #	None	把所有东西打包进.exe文件中
    
    from distutils.core import setup
    import py2exe
    
    
    includes = ["encodings", "encodings.*",'decimal'];
    
    options = {
        "py2exe": {"compressed":1,
        "optimize":0,
        "includes":includes,
        "bundle_files":1}
    };
    
    setup(
        version = "0.0.1",
        description = "描述",
        name = "程序名",
        options = options,
        zipfile=None,
        windows=[{
            "script": "transferEngergyData.py",
            #"icon_resources": [(1, "logo.ico")],
            "dest_base":"StartLink",    #输出程序的名称,没有此项的话默认为主script的文件名main
            "author": "作者",
            'description':u"程序描述信息",
            'copyright':u'(C) www.company.com Inc.  All rights reserved.', 
            'company_name':u"公司名称"
        }],
    	data_files=[("",
    				["config.ini", "time.txt"]),  
                   ],
    )
    

     2. Q&A

    py2exe打包[Q&A]

    RuntimeError: Unable to import decimal

    http://www.py2exe.org/index.cgi/PyODBC

    name '__file__' is not defined

    http://www.py2exe.org/index.cgi/WhereAmI

    路径设置

     1 def we_are_frozen():
     2     """Returns whether we are frozen via py2exe.
     3     This will affect how we find out where we are located.""" 
     4     
     5     return hasattr(sys, "frozen") 
     6 
     7 def module_path():
     8     """ This will get us the program's directory,
     9     even if we are frozen using py2exe"""
    10 
    11     if we_are_frozen():
    12         return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
    13 
    14     return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
    15     
    16 current_path = module_path()
    17 
    18 logger=Logger(logname='%s\\log.txt' %current_path,loglevel=1,logger='DataTransmission').getlog()
    19 hour_file='%s\\time.txt' %current_path
    View Code

    3.指定的服务已经标记为删除

    4. 怎样设定windows服务的启动顺序 http://jingyan.baidu.com/article/86f4a73e37381e37d65269b7.html

  • 相关阅读:
    Guava Enums
    Guava CharMatcher
    Guava CaseFormat
    HotSpot Generations
    Java Run-Time Data Areas
    Reloading Java Classes 201: How do ClassLoader leaks happen? Translation
    Guava BiMap AbstractBiMap
    Reloading Java Classes 101: Objects, Classes and ClassLoaders Translation
    Guava CompoundOrdering
    Chapter 4 -- Throwables
  • 原文地址:https://www.cnblogs.com/Amagasaki/p/3586152.html
Copyright © 2011-2022 走看看