禁止子控制台输出(Tkinter的)应用程序
我试图运行在Python应用程序可执行以下代码所做使用禁止子控制台输出(Tkinter的)应用程序
pyinstaller -w -F script.py
:当按下一个按钮的Tkinter
def ffmpeg_command(sec):
cmd1 = ['ffmpeg', '-f','gdigrab','-framerate',config.get('FFMPEG_Settings','Framerate'),'-i','desktop',gen_filename_from_timestamp_and_extension()]
proc = subprocess.Popen(cmd1,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
duration = sec
sleeptime = 0
while proc.poll() is None and sleeptime < duration:
# Wait for the specific duration or for the process to finish
time.sleep(1)
sleeptime += 1
proc.terminate()
上面的代码运行,该代码是从按钮单击处理程序调用。
我的问题是,当我运行的EXE这不运行的ffmpeg。 但是,如果我设置的命令是:
proc = subprocess.Popen(cmd1)
FFMPEG不跑,我得到我想要的电影文件,但我可以看到FFMPEG控制台窗口。所以我最终得到了电影中的控制台窗口。 (我照顾最小化按钮点击处理程序中的Tkinter窗口)
我的问题是我如何取消控制台窗口并仍然按照我想要的方式运行FFMPEG? 我看着下面的线程,但不能使它工作: How to hide output of subprocess in Python 2.7, Open a program with python minimized or hidden
谢谢
谢谢@Stack和@eryksun! 我更改为以下代码:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
cmd1 = ['ffmpeg', '-f','gdigrab','-framerate',config.get('FFMPEG_Settings','Framerate'),'-i','desktop',gen_filename_from_timestamp_and_extension()]
proc = subprocess.Popen(cmd1,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,startupinfo=startupinfo)
实现了我想要的。 事实上,正如@eryksun建议,只将输出重定向没有做到这一点,我不得不使用stdin=subprocess.DEVNULL
以及抑制所有输出。
这仍然留在控制台窗口可见,但通过上述设置startupinfo
,该控制台窗口被隐藏。 也验证了当时间到期时FFMPEG消失。
谢谢你的帮助!
你说你保留'shell = True',但是你没有在上面的代码中使用它,这是最好的,因为这个命令不需要shell。我仍然建议告诉Windows不要通过'DETACHED_PROCESS'创建标志来创建控制台。 – eryksun
尝试添加参数** shell = True ** to proc = subprocess.Popen(cmd1,stdout = subprocess.DEVNULL,stderr = subprocess.DEVNULL) – Stack
@Stack - 感谢您的评论。我试了一下修改于:'proc等于subprocess.Popen(CMD1,壳=真,标准输出= subprocess.DEVNULL,标准错误= subprocess.DEVNULL)'但是如果你使用的是Windows,我仍然得到同样的结果:( –
7或以上,你可能有一个坏的标准输入手柄。通过'标准输入= subprocess.DEVNULL'更换。但是,手柄设置为'NUL'设备不会阻止控制台的分配或隐藏。'壳= True'将通过'STARTUPINFO'隐藏它,但最好避免使用shell,并且最好不要连接到控制台。定义'DETACHED_PROCESS = 8'并使用'creationflags = DETACHED_PROCESS'。 – eryksun