啥也不說了,直接上代碼:
#要先開啟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