【问题标题】:Python Execute Shell commands without having a terminal openPython 在不打开终端的情况下执行 Shell 命令
【发布时间】:2018-11-28 10:31:34
【问题描述】:

我正在编写一个脚本,如果给定应用程序已经运行,则该脚本应该关注它,否则启动该应用程序。

我正在使用subprocess 模块的run() 方法运行一些shell 命令来检查一个实例当前是否正在运行,如果没有则启动一个新实例。

如果从终端执行,该脚本工作得非常好,但是如果通过 Gnome Shell 的键盘快捷键启动,则不会执行任何操作。

我的问题是如何在不打开终端的情况下执行 shell 命令?

这是我用于 shell 命令的代码的 sn-p:

def focus_instance_of(application):
    # Moves the window to the current desktop, raises it und gives it focus
    print("Put " + application + " in focus...")
    subprocess.run(["wmctrl", "-R", application])

【问题讨论】:

标签: python shell terminal subprocess gnome-shell


【解决方案1】:

你如何在“不打开终端”的情况下执行命令(无需 shell)。

如果它从终端正确执行 - 我假设是命令行 - 而不是从 Gnome Shell 执行,那么不同环境的某些功能可能会导致它失败。

我建议你将stdoutstderr 重定向到一个日志文件,这样你就可以开始调试了。检查未处理的异常。还要检查wmctrl执行的输出和返回码,可能会报错。

【讨论】:

    【解决方案2】:

    您可以添加关键字参数shell=True,这将在后台生成一个shell来运行命令(但不打开终端窗口)。

    subprocess.run(["wmctrl", "-R", application], shell=True)
    

    【讨论】:

    • 从 CLI 启动时脚本运行正常这一事实表明问题不在于缺少 shell。此外,wmctrl 没有理由需要 shell。
    最近更新 更多