You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.7中os.system执行ipconfig出现输出乱码的问题

解决Python调用ipconfig命令输出乱码的问题

为什么os.system会出现乱码?

Windows命令行默认编码是GBK(部分旧版本为GB2312),而Python脚本运行的终端通常采用UTF-8编码。用os.system直接调用命令时,输出的GBK编码内容在UTF-8终端中会显示为乱码,而且os.system仅返回命令退出码,无法直接控制输出的编码转换。

更可靠的解决方案:用subprocess模块替代os.system

subprocess是Python官方推荐的执行外部命令的工具,支持直接指定输出编码,能彻底解决乱码问题。示例代码如下:

import subprocess

# 执行ipconfig /release并捕获输出
release_result = subprocess.run(
    ['ipconfig', '/release'],
    capture_output=True,
    text=True,
    encoding='utf-8'
)
print("IP释放结果:")
print(release_result.stdout)
# 打印错误信息(如果有的话)
if release_result.stderr:
    print("错误提示:")
    print(release_result.stderr)

# 执行ipconfig /renew并捕获输出
renew_result = subprocess.run(
    ['ipconfig', '/renew'],
    capture_output=True,
    text=True,
    encoding='utf-8'
)
print("\nIP重新获取结果:")
print(renew_result.stdout)
if renew_result.stderr:
    print("错误提示:")
    print(renew_result.stderr)

参数说明:

  • capture_output=True:捕获命令的标准输出和错误输出
  • text=True:以文本模式处理输出(替代旧版本的universal_newlines=True)
  • encoding='utf-8':将命令输出转换为UTF-8编码,避免乱码

坚持用os.system的临时处理方案

如果不想更换模块,可以先把命令行编码切换为UTF-8(代码页65001),再执行ipconfig命令:

import os

# 切换控制台编码为UTF-8,> nul 用于隐藏切换提示
os.system('chcp 65001 > nul')
# 释放IP
os.system('ipconfig /release')
# 重新获取IP
os.system('ipconfig /renew')

这种方法的缺点是切换编码后会影响后续命令的输出编码,且os.system无法捕获输出,只能直接打印,灵活性远不如subprocess。

内容的提问来源于stack exchange,提问作者Gilza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:06:48