如何读取os.Popen/subprocess打开的新命令提示符输出内容?
解决CoreServer.exe新窗口输出无法捕获的问题
问题根源
你尝试的os.popen()、subprocess.Popen+PIPE、check_output都失败,核心原因是你启动了新的命令提示符窗口——CoreServer.exe的标准输出/错误会绑定到这个新窗口,而不是当前Python进程的管道,所以常规的管道捕获方法根本拿不到内容。另外check_output首次无输出是因为进程可能在后台运行未立即输出,二次报错则是服务器的单实例限制导致。
解决方案
方案1:直接启动进程(不新开窗口),捕获管道输出
既然已经处理了管理员权限,直接在当前进程上下文启动CoreServer.exe,就能通过subprocess的管道捕获输出:
import subprocess try: # 直接启动CoreServer,捕获stdout和stderr proc_result = subprocess.run( ["CoreServer.exe"], capture_output=True, text=True, check=True ) print("输出内容:\n", proc_result.stdout) if proc_result.stderr: print("错误信息:\n", proc_result.stderr) except subprocess.CalledProcessError as e: print(f"进程启动失败,返回码: {e.returncode}") print("错误输出:\n", e.stderr) except FileNotFoundError: print("找不到CoreServer.exe,请检查路径")
方案2:必须新开窗口时,通过日志文件捕获输出
如果业务需求必须显示新的命令提示符窗口,可让CoreServer.exe把输出重定向到日志文件,再由Python读取:
import subprocess import time import os LOG_FILE = "core_server_output.log" # 启动时重定向所有输出到日志文件,同时新开窗口 try: proc = subprocess.Popen( ["cmd", "/c", f"CoreServer.exe > {LOG_FILE} 2>&1"], creationflags=subprocess.CREATE_NEW_CONSOLE # 强制新开命令窗口 ) # 等待进程初始化(时间根据实际情况调整) time.sleep(2) # 读取日志内容 if os.path.exists(LOG_FILE): with open(LOG_FILE, "r", encoding="utf-8") as f: output = f.read() print("捕获到的窗口输出:\n", output) # 如需实时监控日志,可取消注释以下代码 # last_pos = 0 # while proc.poll() is None: # with open(LOG_FILE, "r", encoding="utf-8") as f: # f.seek(last_pos) # new_content = f.read() # if new_content: # print(new_content, end="") # last_pos = f.tell() # time.sleep(1) except Exception as e: print(f"启动失败: {str(e)}")
附加:避免单实例启动报错
在启动前检查CoreServer.exe是否已在运行,防止二次启动触发单实例限制:
import psutil def is_core_server_running(): for proc in psutil.process_iter(["name"]): if proc.info["name"].lower() == "coreserver.exe": return True return False # 启动前检查 if not is_core_server_running(): # 执行上述方案1或方案2的启动代码 else: print("CoreServer.exe已经在运行,无法重复启动")
注意:需要先安装psutil库,执行
pip install psutil
内容的提问来源于stack exchange,提问作者nikhil
相关产品推荐
相关产品推荐

