2009-11-17 98 views
2

我想獲取Python中網頁的截圖。爲此,我正在使用http://github.com/AdamN/python-webkit2png/如何殺死通過Python啓動的無頭X服務器?

newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]] 
    for i in range(1, len(sys.argv)): 
     if sys.argv[i] not in ["-x", "--xvfb"]: 
      newArgs.append(sys.argv[i]) 
    logging.debug("Executing %s" % " ".join(newArgs)) 
    os.execvp(newArgs[0], newArgs) 

基本上調用xvfb-運行正確的參數。但man xvfb說:

Note that the demo X clients used in the above examples will not exit on their own, so they will have to be killed before xvfb-run will exit.

因此,這意味着,該腳本將<????>如果整個事件處於循環狀態(要獲取多個屏幕截圖),除非X服務器被終止。我怎樣才能做到這一點?

+0

webkit2png.py應該在截屏後退出,不需要殺死它。 – 2009-11-17 10:10:21

+0

是的,但如果我在webkit2png.py中循環,它不會自行死亡。 – agiliq 2009-11-17 11:06:53

+0

使用無盡('while True')循環而不是僅僅幾次迭代的原因是什麼?(當範圍(n)'')或者'break'時間過了一段時間? – 2009-11-17 11:32:18

回答

4

os.execvp狀態的文檔:

這些功能都執行新的程序 ,取代目前 過程;他們不回來。 [..]

所以在調用os.execvp之後,程序中沒有其他語句會被執行。您可能需要使用subprocess.Popen代替:

subprocess模塊允許您 產卵新工藝,連接到他們的 輸入/輸出/錯誤管道,並獲得他們的 返回代碼。該模塊 打算更換其他幾個, 舊的模塊和功能,如:

使用subprocess.Popen,代碼運行xlogo在虛擬幀緩存的X服務器就變成了:

import subprocess 
xvfb_args = ['xvfb-run', '--server-args=-screen 0, 640x480x24', 'xlogo'] 
process = subprocess.Popen(xvfb_args) 

現在的問題是xvfb-run在後臺進程中啓動Xvfb。調用process.kill()不會殺死Xvfb(至少不在我的機器上...)。我一直在擺弄周圍用這個有點,到目前爲止,這對我的作品的唯一事情是:

import os 
import signal 
import subprocess 

SERVER_NUM = 99 # 99 is the default used by xvfb-run; you can leave this out. 

xvfb_args = ['xvfb-run', '--server-num=%d' % SERVER_NUM, 
      '--server-args=-screen 0, 640x480x24', 'xlogo'] 
subprocess.Popen(xvfb_args) 

# ... do whatever you want to do here... 

pid = int(open('/tmp/.X%s-lock' % SERVER_NUM).read().strip()) 
os.kill(pid, signal.SIGINT) 

所以這個代碼/tmp/.X99-lock讀取Xvfb進程ID和發送過程的中斷。它的工作原理,但不時產生一個錯誤消息(我想你可以忽略它)。希望別人能提供更優雅的解決方案。乾杯。

+0

感謝這一堆:不漂亮,但它工作+1 – jkp 2012-07-25 10:16:19