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
相关产品推荐
相关产品推荐

