【问题标题】:Modify path of execution of a python script running as a windows service修改作为 Windows 服务运行的 python 脚本的执行路径
【发布时间】:2026-01-08 08:50:01
【问题描述】:

我有一个 Python 应用程序,它使用 ConfigParser.ConfigParser() 来访问配置文件。我使用py2exe 创建了 Python 应用程序的 Windows 服务。我遇到的问题是,如果我将配置文件放在windows/system32 文件夹中,服务只能找到配置文件。我希望将配置文件放在安装服务的同一文件夹中。例如,使用py2exe后,我有以下文件夹:

c:/temp/dist/winservice.exe
c:/temp/dist/configfile.cfg

然后我做:

winservice.exe install

但该服务不会在路径:c:/temp/dist/ 而是在路径:c:/windows/system32/ 中查找 configfile.cfg

有什么办法可以改变吗?

谢谢!

【问题讨论】:

    标签: python windows-services py2exe configparser


    【解决方案1】:

    您可以使用 Inspect 模块来获取创建此代码对象的文件的名称。 因此,要获取您将使用的文件的路径:inspect.currentframe().f_code.co_filename

    所以,要获取你的 winservice.exe 所在的目录名称:

    dirPath = os.path.dirname(inspect.currentframe().f_code.co_filename)

    希望对你有帮助

    【讨论】:

    • 感谢您的回答@Alexander。我已经尝试过你的建议,dirPath 是空的。我正在做configFile = os.path.join(os.path.dirname(dirPath),'config.cfg') 并且configFile 等于“config.cfg”。问题是,如果我将文件放在 c:/windows/system32/ 路径中,服务只会找到该文件。