'prevent pydub from opening console window
Is there a way to prevent pydub from opening a console window when using ffmpeg (on Windows) ? Each time it launches ffmpeg to convert a mp3 file to wav, it briefly opens a console window that shuts down automatically when process is done but can be disturbing.
Solution 1:[1]
The solution I am using is to overload the from_file function. I just changed subprocess call, adding option startupinfo. Here are the few lines I added:
import platform
systeme = platform.system()
if systeme == 'Windows':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
p = subprocess.Popen(conversion_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
else:
p = subprocess.Popen(conversion_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)`
Solution 2:[2]
I do the following in any script which uses pydub:
Add import subprocess before import pydub
Then, just before I use pydub in the script I add:
if subprocess.mswindows:
subprocess.STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
This tells any subprocess call from that script (whether or not through a pydub instruction) to not display a window by default, but to look to another flag called wShowWindow to decide whether to display. As that flag is 0 by default, the window isn't shown.
Solution 3:[3]
You can modify the source code and recompile it at runtime.
# Created by [email protected] at 2022/2/18 22:09
import importlib.util
import re
import sys
import types
import pydub
from IceSpringPathLib import Path
for moduleName in "pydub.utils", "pydub.audio_segment":
spec = importlib.util.find_spec(moduleName, None)
source = spec.loader.get_source(moduleName)
snippet = "__import__('subprocess').STARTUPINFO(dwFlags=__import__('subprocess').STARTF_USESHOWWINDOW)"
source, n = re.subn(r"(Popen)\((.+?)\)", rf"\1(\2, startupinfo=print('worked') or {snippet})", source, flags=re.DOTALL)
module = importlib.util.module_from_spec(spec)
exec(compile(source, module.__spec__.origin, "exec"), module.__dict__)
sys.modules[moduleName] = module
module = importlib.reload(sys.modules["pydub"])
for k, v in module.__dict__.items():
if isinstance(v, types.ModuleType):
setattr(module, k, importlib.import_module(v.__name__))
pydub.audio_segment.AudioSegment.from_file(Path("~/Music").expanduser().glob("**/*.mp3").__next__())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tsionyx |
| Solution 2 | dingles |
| Solution 3 | BaiJiFeiLong |
