Python脚本调用PowerShell命令时弹出的快速窗口如何禁用?
隐藏PowerShell弹窗解决方案
你可以通过配置Windows下subprocess的STARTUPINFO参数实现隐藏PowerShell运行窗口,修改后的完整代码如下:
from __future__ import print_function import ctypes, sys import subprocess def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if not is_admin(): if sys.version_info[0] == 3: # 最后一位参数如果改为0,可同时隐藏Python脚本本身的运行窗口 ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) # 配置隐藏窗口的启动参数 startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE cmd = 'PowerShell -Executionpolicy byPass -Command New-NetFirewallRule -DisplayName "System_x64" -Enable True -Profile Any -Action Block -Direction Outbound -RemoteAddress "8.8.8.8"' # 传入startupinfo参数隐藏窗口 check = subprocess.run( "PowerShell -Executionpolicy byPass -Command Get-NetFirewallRule -DisplayName 'System_x64'", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo ) if check.returncode != 0: rs = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo )
核心修改说明
- 新增了
STARTUPINFO配置项,这是Windows系统提供的进程启动参数配置类,通过设置STARTF_USESHOWWINDOW标记和SW_HIDE属性,告诉系统启动新进程时不显示窗口 - 所有调用
subprocess.run和subprocess.Popen执行PowerShell命令的位置,都传入了配置好的startupinfo参数 - 可选优化:如果需要同时隐藏Python脚本本身的运行窗口,可以把
ShellExecuteW的最后一个参数从1改为0
内容的提问来源于stack exchange,提问作者Marwen Kaouena
相关产品推荐
相关产品推荐

