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

如何让Python中os.system不终止后续脚本执行?

解决方法

问题原因

os.system()会阻塞当前Python进程,直到传入的Shell命令完全执行结束才会继续向下运行。这里feh ./img/是交互式图像查看工具,会持续运行到你手动关闭窗口,导致后续的rm -rf ./img/和print语句都被卡住;如果feh意外退出,也可能因Shell命令的执行状态导致流程中断,但核心问题是os.system()的阻塞特性。

方案1:用subprocess.Popen实现非阻塞执行

使用Python标准库subprocess的Popen方法,它不会阻塞主进程,能让Python脚本继续执行后续代码,同时Shell命令在后台完成:

import subprocess

# 将Shell命令放到后台执行,避免终端信号影响主进程
subprocess.Popen(
    "feh ./img/ && rm -rf ./img/",
    shell=True,
    start_new_session=True,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL
)

print("This will print now")
  • shell=True允许执行完整的Shell命令串;
  • start_new_session=True让子进程脱离当前Python进程的会话,避免终端关闭中断它;
  • stdout/stderr=subprocess.DEVNULL可以屏蔽feh的输出信息,避免干扰Python脚本的正常输出。

方案2:线程分离执行(适合需后续联动的场景)

如果你想在feh关闭、img目录删除后执行额外操作,但又不想阻塞当前脚本的其他逻辑,可以用线程分离任务:

import subprocess
import threading

def run_feh_and_clean():
    subprocess.run("feh ./img/ && rm -rf ./img/", shell=True)
    # 可在此添加feh关闭后的后续操作

# 启动守护线程执行命令
threading.Thread(target=run_feh_and_clean, daemon=True).start()

print("This prints immediately")
# 继续执行脚本的其他逻辑

为什么不推荐os.system()?

os.system()是老旧的API,功能受限,只能阻塞等待命令执行,无法灵活控制子进程的运行状态,Python官方已明确推荐使用subprocess模块替代它。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:40:17