描述如何在windows中添加.pyw脚本

2024-10-02 14:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分发一个简单的库/应用程序,其中包括一个带有GUI的脚本。在windows下我想让它运行pythonw.exe,最好是使其成为.pyw文件。在

root/
    lib/
        lib.py

    guiscript.py
    setup.py

我希望用户能够在任何路径中安装guiscript。在

我从this question:偷了这个钩子

^{pr2}$

但这不起作用,因为它改变了guiscript.py在源文件夹中,因为路径相对于设置.py. 在

有没有一个合理的方法来获取脚本安装路径,或者是另一个简单的方法来查找guiscript.py(不是给的,是Python的)。在


因为我没有50个业力,所以我无法在7小时内回复自己的帖子,但这里是:

好吧,我找到了解决办法。如果你愿意,我可以删除这个问题,但现在我会保留它,以防其他人有同样的问题。在

from distutils.core import setup
from distutils.command.install_scripts import install_scripts
import os, sys

class my_install(install_scripts):
    """Change main script to .pyw after installation.

    If sys.argv == '-remove'; it's ran as uninstall-script.
    Override run() and then call parent."""
    def run(self):
        install_scripts.run(self)
        try:
            if (sys.platform == "win32") and sys.argv[1] != "-remove":
                for script in self.get_outputs():
                    if script.endswith("guiscript.py"):
                        os.rename(script, script+"w")
        except IndexError:pass

setup(...
      cmdclass={"install_scripts": my_install}
     )

Tags: install方法runpyimportself路径脚本