【问题标题】:Run os.system commands in new terminal - Python 3 on Raspberry Pi在新终端中运行 os.system 命令 - Raspberry Pi 上的 Python 3
【发布时间】:2018-11-16 06:35:27
【问题描述】:

我正在运行一个程序,该程序根据用户在我的 Raspberry Pi 上收到的输入运行终端代码。我希望该进程在我的 python 代码打开的不同终端上运行。 为此,我在我的 Ubuntu 机器上做了

os.system("gnome-terminal -x google-chrome") #if i wanted to open chrome

但这不是 raspbian 拉伸的选项。我想知道如何在我的树莓派上执行类似的功能

我曾问过类似的问题here。参考它以更好地理解我的要求

我在运行 Raspbian Stretch 的 Raspberry Pi 模型 2 B 上安装了 Python 3.5.3

【问题讨论】:

  • “在不同的终端上运行”是什么意思?你是否被 Python 终端中 Chrome 的输出所困扰?还是您希望 Python 代码继续与 Chrome 并行运行?
  • 我需要 python 代码并排运行。因为当我打开 chrome(或任何其他应用程序)时,它会在与 python 代码相同的终端上启动,这会阻止我进一步输入代码
  • 我认为它在 Raspberry Pi 中不起作用,因为没有安装 gnome-terminal。您可以尝试将其替换为os.system("LXTerminal -x google-chrome")。我从来没有尝试过这个,因为我不在我的树莓派上使用 GUI。
  • 我尝试过“lxterminal -x”,但没有成功

标签: python python-3.x raspberry-pi


【解决方案1】:

听起来您不一定想生成一个新的终端模拟器来运行一个进程,而只是希望该进程与您的 Python 代码并行运行。您可以使用subprocess 模块以比os.system 更灵活的方式生成新进程。

import subprocess
subprocess.Popen("google-chrome", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Python code continues executing as soon as the process is spawned
print("Hello, World!")

stdoutstderr 参数表明应该丢弃输出(即重定向到 /dev/null)。

请注意,默认情况下Popen 不使用 shell 来运行您的命令。如果您想更接近地模拟os.system 的行为,请使用shell=True 作为Popen 的参数。与os.system 一样,这可能会产生安全隐患!

【讨论】:

  • 成功了,谢谢。虽然我需要在 Popen 中添加shell=True
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多