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

如何在Python的os.system命令中传递变量?附磁盘重扫示例

正确传入disk_name变量的方法及优化方案

先修正你代码中的两个错误:

  • disk_name = sda 缺少字符串引号,Python会将sda识别为未定义的变量,正确写法是 disk_name = "sda"
  • 命令拼接方式错误,你错误地将整个命令用引号包裹后再用+拼接,导致语法错误和命令格式异常

正确的命令拼接方法

方法1:使用f-string(Python 3.6+ 推荐写法)

#!/usr/bin/python3
import os

disk_name = "sda"
command = f"echo 1 > /sys/block/{disk_name}/device/rescan"
os.system(command)

方法2:使用str.format()

#!/usr/bin/python3
import os

disk_name = "sda"
command = "echo 1 > /sys/block/{}/device/rescan".format(disk_name)
os.system(command)

更优的实现方案

直接用Python原生文件操作写入内容,无需调用shell命令,更安全高效,还能避免潜在的shell注入风险:

#!/usr/bin/python3

disk_name = "sda"
rescan_file = f"/sys/block/{disk_name}/device/rescan"

# 打开文件并写入"1"
with open(rescan_file, 'w') as f:
    f.write("1")

如果偏好使用subprocess模块(比os.system更规范),可以这样写:

#!/usr/bin/python3
import subprocess

disk_name = "sda"
rescan_file = f"/sys/block/{disk_name}/device/rescan"

# 无需shell=True,直接将echo的输出重定向到目标文件
with open(rescan_file, 'w') as f:
    subprocess.run(["echo", "1"], stdout=f, check=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:36:20