Python 在不打开终端的情况下执行 Shell 命令
Python Execute Shell commands without having a terminal open
我正在编写一个脚本,如果它已经 运行ning 则应该关注给定的应用程序,否则将启动该应用程序。
我正在使用 subprocess
模块的 run()
方法来 运行 一些 shell 命令来检查实例当前是否 运行宁,如果不开始一个新的。
如果从终端执行,该脚本工作得很好,但是如果从 Gnome Shell 通过键盘快捷键启动,则它什么也做不了。
我的问题是如何在不打开终端的情况下执行 shell 命令?
这是我用于 shell 命令的代码片段:
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])
您可以添加关键字参数 shell=True
,这将在后台生成一个 shell 到 运行 命令(但不会打开终端 window)。
subprocess.run(["wmctrl", "-R", application], shell=True)
这是执行命令的方式(不需要shell)"without having a terminal open"。
如果它从终端 - 命令行正确执行,我假设 - 而不是从 Gnome Shell,那么不同环境的某些特性可能会导致它失败。
我建议您将 stdout
和 stderr
重定向到一个日志文件,这样您就可以开始调试了。检查未处理的异常。还要检查wmctrl
执行的输出和return代码,可能是报错了。
我正在编写一个脚本,如果它已经 运行ning 则应该关注给定的应用程序,否则将启动该应用程序。
我正在使用 subprocess
模块的 run()
方法来 运行 一些 shell 命令来检查实例当前是否 运行宁,如果不开始一个新的。
如果从终端执行,该脚本工作得很好,但是如果从 Gnome Shell 通过键盘快捷键启动,则它什么也做不了。
我的问题是如何在不打开终端的情况下执行 shell 命令?
这是我用于 shell 命令的代码片段:
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])
您可以添加关键字参数 shell=True
,这将在后台生成一个 shell 到 运行 命令(但不会打开终端 window)。
subprocess.run(["wmctrl", "-R", application], shell=True)
这是执行命令的方式(不需要shell)"without having a terminal open"。
如果它从终端 - 命令行正确执行,我假设 - 而不是从 Gnome Shell,那么不同环境的某些特性可能会导致它失败。
我建议您将 stdout
和 stderr
重定向到一个日志文件,这样您就可以开始调试了。检查未处理的异常。还要检查wmctrl
执行的输出和return代码,可能是报错了。