2010-04-30 125 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

相關問題