python 如何编写 运行 另一个 python 程序,就好像它是从单独的 SSH 终端 运行 一样?

how can python program run another python program as if it is being run from separate SSH terminal?

在 Raspberry Pi 2 运行ning Jessie 上,我有两个显示器,一个(默认)HDMI 显示器和一个 LCD 触摸屏(需要设置几个与 SDL 相关的变量使用 os.environ).

我有两个 pygame 程序,lcd.py 和 hdmi.py,当来自不同 SSH 终端的 运行 很好地共存时,lcd.py dsiplays几个按钮,hdmi.py 在连接的 HDMI 显示器上显示幻灯片。

如果我 运行 它们分别在两个 SSH 终端(作为 'pi' 用户,使用 sudo python PROGRAM),lcd.py 显示到 LCD 和 hdmi.py 在 HDMI 屏幕上显示幻灯片。

但是,我不知道如何让 lcd.py 调用 hdmi.py 程序作为一个完全独立的进程(因此它有自己的环境变量,并且可以独立于驱动 LCD 显示器的父进程)。

lcd.py 程序有一个按钮,触摸该按钮会调用例程 startSlideShow()

但是,我在 lcd.py startSlideShow() 中尝试启动 hdmi.py 的各种操作都失败了:

def startSlideShow():
   # when running in SSH the correct command is 
   #     sudo python /home/pi/Desktop/code/hdmi.py
   # or  sudo /usr/bin/python /home/pi/Desktop/code/hdmi.py
   # tried various ways of invoking hdmi.py via
   # os.fork(), os.spawnl(), subprocess.Popen()
   WHAT GOES HERE?

不需要正在进行的进程间通信。 除了 lcd.py 程序需要 "launch" hdmi.py 程序,它们不需要通信,终止 lcd 是否终止 hdmi.py 程序对我来说并不重要。

我在 startSlideShow() 中尝试过的没有的方法:

cmd = "sudo /usr/bin/python /home/pi/Desktop/code/hdmi.py"
pid = os.spawnl(os.P_NOWAIT, cmd)
# lcd.py keeps running, but creates a zombie process [python]<defunct>  instead of running hdmi.py

cmd = "sudo /usr/bin/python /home/pi/Desktop/code/hdmi.py"
pid = os.spawnl(os.P_DETACH, cmd)
# lcd.py exits with error AttributeError: 'module' object has no attribute 'P_DETACH'

cmd = "sudo /usr/bin/python /home/pi/Desktop/code/hdmi.py"
pid = os.spawnl(os.P_WAIT, cmd)
# no error message, returns a pid of 127, but does nothing, and no such process exists when I run `ps aux` in another SSH terminal

cmd = ["/usr/bin/python", "/home/pi/Desktop/code/hdmi.py" ]
pid = subprocess.Popen(cmd, stdout=subprocess.PIPE).pid # call subprocess
# runs the hdmi.py program, but output goes to LCD not HDMI 
# (the 2 programs alternately take over the same screen) 

cmd = ["/usr/bin/python", "/home/pi/Desktop/code/hdmi.py" ]
pid = subprocess.Popen(cmd).pid
# as above, both programs run on same display, which flashes between the two programs

pid = os.spawnlp(os.P_NOWAIT, "/usr/bin/python",  "/home/pi/Desktop/code/hdmi.py")
# invokes python interpreter, get >>> on SSH terminal

pid = os.spawnlp(os.P_NOWAIT, "/usr/bin/python /home/pi/Desktop/code/hdmi.py")
# creates zombie process [python] <defunct>

为了给子进程一个不同于父进程的环境变量值,你可以使用 env 参数给 POpen 构造函数并提供你想要的值。例如,这应该允许您提供不同的 DISPLAY 值。