【问题标题】:Running a bash script from Python从 Python 运行 bash 脚本
【发布时间】:2023-09-18 03:28:01
【问题描述】:

我需要从 Python 运行一个 bash 脚本。我让它按如下方式工作:

import os
os.system("xterm -hold -e scipt.sh")

这不是我正在做的,而是我的想法。效果很好,会打开一个新的终端窗口,我将其保留用于调试目的,但我的问题是即使没有完成,我也需要 python 脚本继续运行。有什么办法可以做到吗?

【问题讨论】:

    标签: python linux bash


    【解决方案1】:

    我建议你使用subprocess 模块:docs

    你可以

    import subprocess
    
    cmd = "xterm -hold -e scipt.sh"
    # no block, it start a sub process.
    p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    # and you can block util the cmd execute finish
    p.wait()
    # or stdout, stderr = p.communicate()
    

    有关更多信息,请阅读文档,:)。

    修改拼写错误

    【讨论】:

    • 工作完美。谢谢!