簡體   English   中英

用python和py2exe編寫的Windows Service上的問題

[英]Problems on Windows Service written in python and py2exe

我已經為Windows編寫了一項服務:

agentservice.py

import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import agent

class AgentService(win32serviceutil.ServiceFramework):
    _svc_name_ = "AgentService"
    _svc_display_name_ = "AgentService"
    _svc_deps_ = ["EventLog"]
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcRun(self):
        import servicemanager
        agent.verify()
        # Write a 'started' event to the event log...
        win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STARTED,0,     servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))

        # wait for beeing stopped...
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

        # and write a 'stopped' event to the event log.
        win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STOPPED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AgentService)

然后是agent.py

import os
import socket
import time
import json
import platform
PLATFORM = platform.system()
import uuid
import sys


HOST = 'highwe.net'
PORT = 8302
USERKEY = None


def getHoldHost():
    hold_host = os.environ.get('HOLDHOST')
    if hold_host is None:
        return HOST
    return hold_host
HOST = getHoldHost()


def macAddress():
    return ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0, 8 * 6, 8)][::-1])


def getRelease():
     '''Get OS info'''
    release = ''
    if PLATFORM == 'Windows':
        release = osAction("ver").decode('gbk')
    return release


def getExpInfo(just_info=False):
    '''Get Exception'''
    import traceback
    if just_info:
        info = sys.exc_info()
        return info[0].__name__ + ':' + str(info[1])
    else:
        return traceback.format_exc()


def osAction(command):
    '''
    run command
    '''
    try:
        p = os.popen(command)
        content = p.read()
        p.close()
    except Exception:
        content = 'djoin_error:' + getExpInfo(True)
    return content

def socketAgent():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))
    return sock

def diskMon():
    mon_data = None
    if PLATFORM == 'Windows':
        disk = osAction("wmic logicaldisk get caption, size, freespace, drivetype")
        mon_data = dict(disk=disk)
    else:
        pass
    return mon_data

def send():
    mac = macAddress()
    release = getRelease()
    try:
        sock = socketAgent()
        while True:
            if disk:
                message = json.dumps(dict(user_key=USERKEY, platform=PLATFORM, mac=mac, release=release, mon_data=disk, type="disk")) + '\u7ed3\u675f'
                sock.send(message)
                print '%s send disk' % PLATFORM
            time.sleep(5)
    except socket.error:
        error_info = getExpInfo(True)
        print HOST
        print error_info
        time.sleep(5)
        send()

def verify():
    global USERKEY
    with open('agent.conf', 'r') as f:
        out_data = f.read()
        USERKEY = json.loads(out_data).get('user_key')
    #print 'start...'
    agentPid = os.getpid()
    writePid(agentPid)
    send()

def writePid(pid):
    pid = str(pid)
    with open('pid.config','w') as f:
        f.write("%s\n" % pid)

if __name__ == '__main__':
    pass

注意:agent.conf也在當前目錄中。

agent.conf

{"user_key": "cd7eab88-3055-4b1d-95a4-2ad80731d226"}

而我的setup.py是:

from distutils.core import setup
import py2exe
import sys

sys.argv.append("py2exe")

setup(service = ["agentservice"])

我跑步后:

 python setup.py

./dist目錄中有一個agentservice.exe。 並運行:

agentservice.exe -install 

一切正常,該服務顯示在Windows服務列表中。安裝成功。

但是令我困惑的是:為什么我的服務無法正常啟動和停止? 我的代碼中有錯誤嗎?

任何幫助將不勝感激。

注意:agent.conf也在當前目錄中。

怎么樣? 當前目錄是啟動程序時所在的目錄。 服務的工作目錄通常是您的System32目錄,安裝時的工作目錄是項目下的dist目錄,並且客戶端腳本的工作目錄可能是項目的頂層。 除非您已創建硬鏈接/交界點,否則文件不會同時出現在所有三個位置。

如果要查找腳本目錄中文件,則必須明確地執行此操作。 您可以在啟動時將當前目錄更改為腳本目錄,或將服務配置為從腳本目錄而不是默認位置運行,或者更好的是,您可以忽略當前工作目錄; 在啟動時使用os.path.abspath(os.path.dirname(sys.argv[0]))獲取腳本目錄,然后將os.path.join到路徑中。

但是對於您而言,您已經在使用適當的setup.py ,因此您真正想做的是將文件作為數據或其他文件包含在包中,並使用pkg_resources在運行時定位它。 py2exe可能有其自己的變體,可以代替setuptools東西。如果是這樣,當然可以使用它。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM