简体   繁体   English

运行 Python 脚本,参数为 Windows 服务

[英]Run Python script with parameter as Windows Service

I created a Windows Service with python.我用 python 创建了一个 Windows 服务。 It works well when I run it with debug mode, but when I start the service it doesn't work.当我以调试模式运行它时它运行良好,但是当我启动服务时它不起作用。 This is the sample of my script:这是我的脚本示例:

def run(param):
    subprocess.Popen(["C:\\SER\\txt_write.pyw",param], shell=True)
#txt_write is a simple script: put the parameter into b.txt

def add_param():
    x="123456"
    run(x)

class PythonCornerExample(SMWinservice):
    _svc_name_ = "name"
    _svc_display_name_ = "name disp"
    _svc_description_ = "desc"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        i=0
        while self.isrunning:
            add_param()
            f= open("C:\\SER\\a.txt","a+")
            f.write("xyz")
            f.close()
            
            time.sleep(25)

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

So, when I run this script in debug mode it put "xyz" text into a.txt, and calls another python script, that put the parameter (123456) into b.txt.因此,当我在调试模式下运行此脚本时,它会将“xyz”文本放入 a.txt,并调用另一个 python 脚本,将参数 (123456) 放入 b.txt。 This is how I want it to works.这就是我希望它的工作方式。

My problem is, installed as Windows Service the a.txt works, but b.txt doesn't.我的问题是,安装为 Windows 服务 a.txt 有效,但 b.txt 无效。

What is wrong with my script?我的脚本有什么问题? Why is it OK in debug mode, and why is it wrong as Services?为什么在调试模式下它可以,为什么它作为服务出错?

change last 2 lines with bellow code:用下面的代码改变最后两行:

import servicemanager, sys
if __name__ == '__main__':
  if len(sys.argv) == 1:
    servicemanager.Initialize()
    servicemanager.PrepareToHostSingle(PythonCornerExample)
    servicemanager.StartServiceCtrlDispatcher()
else:
    PythonCornerExample.parse_command_line()

The arguments passed by the service start are in the args parameter of the constructor method of your class.服务启动传递的arguments在你的class的构造方法的args参数中。

class AppServerSvc (win32serviceutil.ServiceFramework):   

def __init__(self, **args**):

You want them in sys.argv, where you'd get them if the parameters were coming from a command line.您希望它们在 sys.argv 中,如果参数来自命令行,您将在其中获取它们。

So I simply did this.所以我只是这样做了。

sys.argv = args

And now I'm parsing my service parameters as if it came from the command line.现在我正在解析我的服务参数,就好像它来自命令行一样。

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM