将CMD命令与可执行的python脚本一起使用
在编写了下面的脚本(它工作得很好)之后,我打开将CMD命令与可执行的python脚本一起使用,python,python-3.x,windows,executable,pyinstaller,Python,Python 3.x,Windows,Executable,Pyinstaller,在编写了下面的脚本(它工作得很好)之后,我打开cmd.exewindows提示符并键入以下内容 pyinstaller -F --windowed myscript.py 这给了我一个名为“myscript.exe”的文件 问题是当我打开可执行文件并按下按钮时,什么都没有发生。我认为这条线有一个问题: check_output("shutdown -s -t 60", shell=True) 即使脚本“作为脚本”工作,它也不能作为可执行文件工作。 我尝试过其他语法,比如 os.syste
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()
我能做什么?你能做什么: 使用:
import subprocess
subprocess.call(["shutdown", "-f", "-s", "-t", "60"])
这会奏效的。带--窗口的
似乎检查输出时有问题,使用--窗口标记:/
Edit1:
根据评论。我的研究结果也是如此,但现在似乎证明了这一点
使用check\u call
和创建标志来避免创建控制台窗口。例如:CREATE_NO_WINDOW=0x08000000;检查调用('shutdown-s-t 60',creationflags=CREATE\u NO\u 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
Edit2:
您还可以直接使用pyinstaller添加图标…
参考:使用check\u call
和创建标志来避免创建控制台窗口。例如:CREATE\u NO\u window=0x08000000;
check\u call('shutdown-s-t 60',creationflags=CREATE\u NO\u window)
。关于检查输出
,由于它覆盖了stdout
,Popen
还必须复制现有stdin和stderr句柄的可继承副本。如果它们无效,这将失败。在Windows 7中从控制台运行时,GUI可以继承无效的标准句柄。解决方法是覆盖所有3个句柄。For示例:output=check\u output('shutdown-s-t 60',stdin=subprocess.DEVNULL
,stderr=subprocess.DEVNULL,creationflags=CREATE\u NO\u WINDOW)
。使用上述方法对上述脚本有效,但当我尝试使用较长的脚本时,按钮不知何故打开了应用程序的另一个实例。编辑:有时有效(较长的脚本),有时不会。有时按钮会在不执行命令的情况下打开程序的另一个实例。我创建了两个可执行文件,然后将它们放在同一个目录中,它们都不起作用,当我删除其中一个时,另一个神奇地开始起作用。@SinaUser,我们没有足够的信息。使用日志记录写入错误,而不是依赖于将信息打印到stdout和异常打印到stderr。默认情况下,它们在GUI进程中不可用。