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

Python执行PowerShell命令返回整数?报错'int'无split属性求解

问题分析与解决方案:Python执行PowerShell命令返回整数导致报错

问题原因

你遇到的AttributeError本质是对os.system()的返回值理解偏差!os.system()执行命令后,返回的不是命令的输出内容,而是命令执行的退出状态码——这是个整数:

  • 返回0表示命令执行成功
  • 返回非0值表示命令执行失败(比如权限不足、路径错误等)

你把这个整数当成字符串去调用.split()方法,自然会触发'int' object has no attribute 'split'的错误。而且os.system()会把命令的输出直接打印到控制台,根本不会把输出内容赋值给你的变量policyINAppconfigFile。

解决方案:改用subprocess模块

Python官方早就推荐用subprocess模块替代os.system(),它能更灵活地控制命令执行,还能捕获命令的输出内容。下面是两种可行的修改方案:

方案1:用subprocess.run()(推荐,功能更全面)

import subprocess

try:
    # 执行PowerShell命令并捕获输出
    cmd_result = subprocess.run(
        [
            r'%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe',
            '-Command',
            'findstr "maxAllowedContentLength" C:\\Windows\\sysnative\\inetsrv\\config\\applicationHost.config'
        ],
        capture_output=True,
        text=True,
        check=True
    )
    
    # 从输出中提取数字
    numbers = []
    for word in cmd_result.stdout.split():
        if word.isdigit():
            numbers.append(int(word))
    
    print(numbers)
except subprocess.CalledProcessError as e:
    print(f"命令执行失败: {e.stderr}")

参数说明:

  • capture_output=True:捕获命令的标准输出和错误输出
  • text=True:将输出以字符串(而非字节流)的形式返回
  • check=True:如果命令执行失败(退出状态码非0),自动抛出异常,方便排查问题
  • cmd_result.stdout就是命令的输出内容,这才是你需要处理的字符串

方案2:用subprocess.check_output()(更简洁,仅获取输出)

如果只需要获取命令的标准输出,不需要处理复杂的错误逻辑,可以用这个更简洁的写法:

import subprocess

try:
    # 获取命令输出
    output = subprocess.check_output(
        [
            r'%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe',
            '-Command',
            'findstr "maxAllowedContentLength" C:\\Windows\\sysnative\\inetsrv\\config\\applicationHost.config'
        ],
        text=True
    )
    
    # 用列表推导式提取数字,更简洁
    numbers = [int(word) for word in output.split() if word.isdigit()]
    print(numbers)
except subprocess.CalledProcessError:
    print("命令执行失败,请检查权限或路径是否正确")

额外注意事项

  • 权限问题:读取applicationHost.config需要管理员权限,运行Python脚本时记得右键选择「以管理员身份运行」,否则命令会执行失败
  • 路径写法:用原始字符串(前缀r)可以避免反复转义反斜杠,让路径更易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:17:26