Skip to content

Instantly share code, notes, and snippets.

@syfun
Last active May 3, 2017 08:54
Show Gist options
  • Save syfun/00df5eec10e0898da38d342de31ae215 to your computer and use it in GitHub Desktop.
Save syfun/00df5eec10e0898da38d342de31ae215 to your computer and use it in GitHub Desktop.
Python snippet
# coding=utf-8
import sys
import re
from flask.cli import main
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
# coding=utf-8
import logging
import os
import sys
import time
from logging import StreamHandler
from logging.handlers import RotatingFileHandler
import win32serviceutil
import winerror
import servicemanager
import win32event
import win32service
from gevent.wsgi import WSGIServer
# sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from plm_cloud import create_app
def get_logger(log_file):
logger = logging.getLogger('upload')
logger.setLevel('INFO')
formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(name)s %(message)s '
'[in %(pathname)s:%(lineno)d]')
rotating_handler = RotatingFileHandler(
log_file, maxBytes=100 * 1024 * 1024, backupCount=200)
rotating_handler.setLevel('INFO')
rotating_handler.setFormatter(formatter)
stream_handler = StreamHandler()
stream_handler.setLevel('INFO')
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.addHandler(rotating_handler)
return logger
class PLMService(win32serviceutil.ServiceFramework):
_svc_name_ = 'PLMService'
_svc_display_name_ = 'PLMServiceS'
_svc_description_ = 'Kelvin PLM Service for Windows.'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.app = create_app('default')
def SvcDoRun(self):
host = self.app.config['HOST']
port = self.app.config['PORT']
self.http_server = WSGIServer(
(host, port), self.app
)
self.http_server.serve_forever()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.http_server.stop(10)
if __name__ == '__main__':
if len(sys.argv) == 1:
print sys.argv
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(PLMService)
servicemanager.Initialize('PLMService', evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error, details:
if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(PLMService)
# write json to file with utf-8 encode.
with codecs.open('out.json', 'w', 'utf-8') as f:
f.write(json.dumps(CHINESE, indent=2, ensure_ascii=False))
# read json from file with utf-8 encode.
with open(file, 'rb') as f:
kv = json.load(f, 'utf-8')
# function argument None
def test(name=None):
name = name or ''
# coding=utf-8
import os
import servicemanager
import sys
import time
import win32event
import win32service
import win32serviceutil
import winerror
class Upload(win32serviceutil.ServiceFramework):
_svc_name_ = 'Upload'
_svc_display_name_ = 'Upload'
_svc_description_ = 'Upload'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.run = True
def SvcDoRun(self):
while self.run:
time.sleep(2)
def SvcStop(self):
# 服务已经停止
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False
if __name__ == '__main__':
if len(sys.argv) == 1:
print sys.argv
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(Upload)
servicemanager.Initialize('Upload', evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error, details:
if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(Upload)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment