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

时间:2016-01-25 01:17:23

标签: python subprocess

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

我有两个pygame程序,lcd.py和hdmi.py,当它们从不同的SSH终端运行时,很好地共存,lcd.py设备上有几个按钮,hdmi.py在附加的HDMI显示屏上显示幻灯片。

如果我在两个SSH终端中单独运行它们(作为'pi'用户,使用sudo python PROGRAM),液晶显示屏上将显示lcd.py,hdmi.py会在HDMI屏幕上显示幻灯片。< / p>

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

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程序需要“启动”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>

1 个答案:

答案 0 :(得分:2)

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