How do you run a Python script as a service in Windows?

后端 未结 13 1956
你的背包
你的背包 2020-11-22 02:18

I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which prov

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 02:38

    pysc: Service Control Manager on Python

    Example script to run as a service taken from pythonhosted.org:

    from xmlrpc.server import SimpleXMLRPCServer
    
    from pysc import event_stop
    
    
    class TestServer:
    
        def echo(self, msg):
            return msg
    
    
    if __name__ == '__main__':
        server = SimpleXMLRPCServer(('127.0.0.1', 9001))
    
        @event_stop
        def stop():
            server.server_close()
    
        server.register_instance(TestServer())
        server.serve_forever()
    

    Create and start service

    import os
    import sys
    from xmlrpc.client import ServerProxy
    
    import pysc
    
    
    if __name__ == '__main__':
        service_name = 'test_xmlrpc_server'
        script_path = os.path.join(
            os.path.dirname(__file__), 'xmlrpc_server.py'
        )
        pysc.create(
            service_name=service_name,
            cmd=[sys.executable, script_path]
        )
        pysc.start(service_name)
    
        client = ServerProxy('http://127.0.0.1:9001')
        print(client.echo('test scm'))
    

    Stop and delete service

    import pysc
    
    service_name = 'test_xmlrpc_server'
    
    pysc.stop(service_name)
    pysc.delete(service_name)
    
    pip install pysc
    

提交回复
热议问题