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

如何将系统命令的执行结果赋值给变量?

如何将系统命令的执行结果赋值给变量

你当前使用system()命令得到的是命令的退出状态码(示例里的0表示命令执行成功),而非命令的输出内容。要把命令的标准输出捕获并赋值给变量,不同环境的实现方式如下:

Shell(Bash/Zsh 等)

在 Shell 环境中,用反引号或**$()**包裹命令,即可将命令输出赋值给变量:

  • 反引号写法:
a=`cat /proc/cpuinfo | grep 'model name' | uniq`
# 查看变量内容
echo $a
  • $()写法(更推荐,嵌套命令时可读性更强):
b=$(xrandr | grep 'current')
# 查看变量内容
echo $b

执行后,变量a和b就会存储对应命令的输出内容,而非退出状态码。

Python 环境

Python 的os.system()仅返回退出状态码,若要捕获命令输出,推荐使用subprocess模块:

import subprocess

# 方式1:使用check_output捕获输出
a = subprocess.check_output("cat /proc/cpuinfo | grep 'model name' | uniq", shell=True, text=True).strip()
print(a)

# 方式2:使用run方法更灵活控制
result = subprocess.run("xrandr | grep 'current'", shell=True, capture_output=True, text=True)
b = result.stdout.strip()
print(b)

注:shell=True允许直接传入管道命令,若不需要管道,建议避免使用以提升安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:45:32