python查看進程是否運行

來源:互聯網
上載者:User

啥也不說了,直接上代碼:

#要先開啟web伺服器才能發推送訊息

#os.system("twistd -r kqueue web --class=pyapns.server.APNSServer --port=7077")

#查看進程是否存在,linux系統中,使用ps -ef|grep twistd來查看進程運行情況,使用axu時會出現twistd進程查不到的情況

def isTwistdRun():

    strtmp = os.popen("ps axu|grep twistd") 

    print type(strtmp)

    cmdback = strtmp.read()

    p = str(cmdback).find('--class=pyapns.server.APNSServer')

    print p

    if not p == -1:

        print 'twistd is run'

        return True

    else:

        print 'twistd is not run'

        return False

        

if not isTwistdRun():

    os.system("twistd -r kqueue web --class=pyapns.server.APNSServer --port=7077") 因為要使用pyapns運行ios推送服務,就要開啟twistd的web伺服器才能給蘋果的發訊息。所以每一次要發推送訊息的時候就要知道twistd有沒有運行。使用上邊的代碼就可以在twistd沒有運行時,自動運行。
python執行系統命令--擷取傳回值

最開始的時候用 Python 學會了 os.system() 這個方法是很多比如 C,Perl 相似的。

os.system('cat /proc/cpuinfo')

但是這樣是無法獲得到輸出和傳回值的,繼續 Google,之後學會了 os.popen()。

output = os.popen('cat /proc/cpuinfo')
print output.read()

通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是怎麼讀取程式執行的傳回值呢,當然咯繼續請教偉大的 Google(聯想到像我這樣的人工作如果離開了 Google,不是成了廢物。。。Baidu 忽視)。Google 給我指向了 commands — Utilities for running commands。
這樣通過 commands.getstatusoutput() 一個方法就可以獲得到傳回值和輸出,非常好用。

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output

Python Document 中給的一個例子,很清楚的給出了各方法的返回。

>>> import commands

>>> commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

參考: http://blog.sina.com.cn/s/blog_5357c0af0100z4rn.html
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.