【问题标题】:Using CMD commands with an executable python script使用带有可执行 python 脚本的 CMD 命令
【发布时间】:2019-01-02 22:33:05
【问题描述】:

写完下面的脚本(完美运行)后,我打开cmd.exe windows 提示符并输入以下内容

pyinstaller -F --windowed myscript.py

这给了我一个名为“myscript.exe”的文件。

问题是当我打开可执行文件并按下按钮时,没有任何反应。我认为这行有问题:

check_output("shutdown -s -t 60", shell=True)  

即使脚本“作为脚本”工作,它也不能作为可执行文件工作。
我尝试过其他语法,例如

os.system("shutdown -s -t 60") 

但它们似乎不起作用。

from tkinter import *
from subprocess import check_output,CalledProcessError

class main_gui:
    def __init__(self,master):
        self.master=master
        master.geometry("250x100")
        self.button1=Button(self.master,
                            text="Press me",
                            font="Times 10 bold",
                            command=self.shutdown)
        self.button1.pack()

    def shutdown(self):
        try:
            check_output("shutdown -s -t 60", shell=True)
            print("Computer will shutdown in 60 seconds")
        except CalledProcessError:
            print("Already pressed")

root = Tk()
my_gui = main_gui(root)
root.mainloop()

我能做什么?

【问题讨论】:

    标签: python python-3.x windows executable pyinstaller


    【解决方案1】:

    你可以做什么:

    使用:

    import subprocess
    subprocess.call(["shutdown", "-f", "-s", "-t", "60"])
    

    这会奏效。 --windowed

    看来check_output--windowed 标志有问题:/

    编辑1:

    基于eryksun cmets。 也是我的研究结果,但现在似乎证明了。

    使用check_call 和创建标志来避免创建控制台窗口。例如:CREATE_NO_WINDOW = 0x08000000; check_call('shutdown -s -t 60', creationflags=CREATE_NO_WINDOW)

    关于check_output,由于它覆盖stdoutPopen 还必须复制现有标准输入和标准错误句柄的可继承副本。如果它们无效,这将失败。在 Windows 7 中从控制台运行时,GUI 可以继承无效的标准句柄。一种解决方法是覆盖所有 3 个句柄。例如:output = check_output('shutdown -s -t 60', stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW

    编辑2:

    你也可以直接用pyinstaller添加图标...
    参考:Windows and Mac OS X specific options

    【讨论】:

    • 使用check_call 和创建标志来避免创建控制台窗口。例如:CREATE_NO_WINDOW = 0x08000000;check_call('shutdown -s -t 60', creationflags=CREATE_NO_WINDOW)
    • 关于check_output,因为它覆盖了stdoutPopen 还必须复制现有stdin 和stderr 句柄的可继承副本。如果它们无效,这将失败。在 Windows 7 中从控制台运行时,GUI 可以继承无效的标准句柄。一种解决方法是覆盖所有 3 个句柄。例如:output = check_output('shutdown -s -t 60', stdin=subprocess.DEVNULLstderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
    • 使用上述方法对上述脚本有效,但是当我尝试使用更长的脚本时,该按钮以某种方式打开了应用程序的另一个实例。
    • 编辑:有时它有效(较长的脚本),有时它不。有时按钮会打开程序的另一个实例而不执行命令。我创建了两个可执行文件,然后将它们放在同一个目录中,它们都不工作,当我删除其中一个时,另一个神奇地开始工作。
    • @SinaUser,我们没有足够的信息。使用logging 将错误写入文件,而不是依赖于将信息打印到stdout 并将异常打印到stderr。默认情况下,它们在 GUI 进程中不可用。