2010-04-30 124 views
0

我想运行一个Python程序来查看屏幕程序是否正在运行。如果是,那么程序不应该运行其余的代码。这是我已经和它不工作:如何判断屏幕是否在运行?

#!/usr/bin/python 

import os 
var1 = os.system ('screen -r > /root/screenlog/screen.log') 
fd = open("/root/screenlog/screen.log") 
content = fd.readline() 

while content: 
if content == "There is no screen to be resumed.": 
    os.system ('/etc/init.d/tunnel.sh') 
    print "The tunnel is now active." 
else: 
    print "The tunnel is running." 
fd.close() 

我知道有可能在这里几件事情,并不需要而且相当多的我失踪。我将在cron中运行这个程序。

回答

-1

也许在第一个os.system调用中重定向的错误消息写在标准错误而不是标准输出上。你应该尝试更换这行:

var1 = os.system ('screen -r 2> /root/screenlog/screen.log') 

注意2>标准错误重定向到文件。

+0

它将它写入文件。当我尝试重定向它时,它不会向该文件写入任何信息。 – spxxn 2010-04-30 16:22:51

2
from subprocess import Popen, PIPE 

def screen_is_running(): 
    out = Popen("screen -list",shell=True,stdout=PIPE).communicate()[0] 
    return not out.startswith("This room is empty") 
+0

也试过这个,没有运气。 – spxxn 2010-04-30 16:23:24

+0

你能发布你的错误信息吗?你正在使用什么版本的Python?屏幕没有安装在运行它的地方吗? – sastanin 2010-04-30 16:43:37

+0

不要忘记,'screen -list'的输出取决于NETHACK选项的值。 :) @spxxn:'screen -list'的输出是什么 – MikeyB 2010-04-30 18:07:56

相关问题