首页 > 解决方案 > 在使用 python 登录之前将应用程序作为服务启动

问题描述

我想在登录之前启动一个 exe,我正在尝试使用 Python 来实现这一点。下面是我尝试使用的示例代码 where SMWinserviceis defined here

# imports are there

class MyService(SMWinservice):
    _svc_name_ = 'testService1'
    _svc_display_name_ = 'Test Service 1'
    _svc_description_ = 'Test ServiceFramework 1 Description'

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        subprocess.Popen(r'C:\Program Files\Notepad++\notepad++.exe')
        # i=0
        # while self.isrunning:
        #     with open('C:\\test1323.txt','a') as file:
        #         file.write(datetime.now().isoformat()+'\n')
        #     i=i+1
        #     time.sleep(5)


if __name__ == '__main__':
    MyService.parse_command_line()

当我只是尝试在文件中写一些东西(在查看这篇文章并解决错误之后)时,上面的代码工作正常。

但是当我尝试启动服务(手动或通过重新启动 PC)时,exe 没有启动,我不明白为什么。我错过了什么或有什么问题?我应该如何处理这样的问题。从 python 的角度来看,我是 Windows 功能的新手。我已经坚持了好几天了,非常感谢任何代码或帮助。

编辑

我将main方法更改为以下。

def main()
    self.process = subprocess.Popen('C:\\Program Files\\Notepad++\\notepad++.exe')
    while self.isrunning:
        if self.process.pid not in psutil.pids():
            self.isrunning = False

        with open('C:\\logs.txt','a') as file:
            file.write(str(self.process.pid)+'\n')

        time.sleep(5)
    self.process.kill()

当我启动进程时,我可以看到进程 pid 正在更新C:\logs.txt。该进程也可以在任务管理器中看到作为notepad++.exe运行。但是应用程序不在前台。有什么想法吗?

标签: pythonwindowsservice

解决方案


这是由于从 Windows Vista 时代起服务无法与 Desktop 交互的限制。


推荐阅读