将CMD命令与可执行python脚本一起使用

时间:2019-01-02 22:33:06

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

在编写完以下脚本(效果很好)之后,我打开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()

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以做什么:

使用:

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

这将起作用。与--windowed

似乎check_output带有--windowed标志存在问题:/

  

编辑1:

基于eryksun条评论。 我的研究结果也是,但现在看来是事实。

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

关于check_output,由于它覆盖stdout,因此Popen还必须复制现有stdin和stderr句柄的可继承副本。如果它们无效,它将失败。从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