将 CMD 命令与可执行 python 脚本一起使用
Using CMD commands with an executable python script
写完下面的脚本(完美运行)后,我打开 cmd.exe
windows 提示符并键入以下内容
pyinstaller -F --windowed myscript.py
这给了我一个名为 "myscript.exe".
的文件
问题是当我打开可执行文件并按下按钮时,没有任何反应。我认为这条线有问题:
check_output("shutdown -s -t 60", shell=True)
即使脚本可以运行 "as a script",它也不能作为可执行文件运行。
我尝试过其他语法,例如
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"])
这行得通。 --windowed
似乎 check_output
和 --windowed
标志有问题 :/
Edit1:
基于 eryksun 评论。 之前也是我的研究成果,现在看来是证据。
使用 check_call
和创建标志来避免创建控制台 window。例如: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
Edit2:
也可以直接用pyinstaller添加图标...
参考:Windows and Mac OS X specific options
写完下面的脚本(完美运行)后,我打开 cmd.exe
windows 提示符并键入以下内容
pyinstaller -F --windowed myscript.py
这给了我一个名为 "myscript.exe".
的文件问题是当我打开可执行文件并按下按钮时,没有任何反应。我认为这条线有问题:
check_output("shutdown -s -t 60", shell=True)
即使脚本可以运行 "as a script",它也不能作为可执行文件运行。
我尝试过其他语法,例如
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"])
这行得通。 --windowed
似乎 check_output
和 --windowed
标志有问题 :/
Edit1:
基于 eryksun 评论。 之前也是我的研究成果,现在看来是证据。
使用 check_call
和创建标志来避免创建控制台 window。例如: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
Edit2:
也可以直接用pyinstaller添加图标...
参考:Windows and Mac OS X specific options