2017-08-02 66 views
1

我有一個函數執行shell命令來部署服務器在機器上。這個函數接受下列參數:輪詢最大的wait_time,除非條件在python 2.7

  • 目錄路徑
  • 命令
  • 服務器端口
  • 等待時間

現在,一旦commanddirectory path內部執行,功能time.sleep s直到wait time,然後檢查在server port上偵聽的進程。

雖然此方法有效,但它爲command s浪費了大量時間,其中啓動所需的時間遠遠少於wait time

我打算創建一個服務員,它將等待最多wait time,但繼續定期輪詢server port。如果在wait time結束之前發現有進程,我希望該函數僅從該點安全返回,並且不要將進程阻塞直到結束。

我不知道如何繼續相同。我能想到的最接近創建一個輪詢對象(使用select.poll),但一個例子(或一個包,如果有的話)會幫助我很多。

我現在的功能做一些類似於:

run_local_command(
    ['nohup', start_command, ">>", logfile, '2>>', errfile, '&'], 
    explanation="Starting server", 
    target_dir=target_dir 
) 
time.sleep(wait_time) 
# Get the PIDs listening to the specific port 
processes = [ 
    p for p in psutil.net_connections(kind='inet') 
    if p.laddr[1] == port and p.status == 'LISTEN' 
] 
logger.debug("Logged following processes for the service port: %s", processes) 
pids = [x.pid for x in processes if x.pid is not None] 

回答

1

我一般用等到條件滿足或直到超時是這樣一個小功能:

def wait_condition(condition, timeout=5.0, granularity=0.3, time_factory=time): 
    end_time = time.time() + timeout # compute the maximal end time 
    status = condition()    # first condition check, no need to wait if condition already True 
    while not status and time.time() < end_time: # loop until the condition is false and timeout not exhausted 
     time.sleep(granularity)  # release CPU cycles 
     status = condition()   # check condition 
    return status      # at the end, be nice and return the final condition status : True = condition satisfied, False = timeout occurred. 

所以,通過給這種方法一個condition方法,當調用和條件滿足時返回True(否則爲False)。

這將循環(並做一些暫停以避免過多的CPU佔用),並在超時結束時或條件爲真時熄滅。

在你的情況,病情的方法可能會做這樣的事情:

def port_opened(): 
    return [p for p in psutil.net_connections(kind='inet') if p.laddr[1] == port and p.status == 'LISTEN'] # assuming that an empty list is False in python 
+0

似乎是一個簡單的方法......說不上來爲什麼我跳入https://stackoverflow.com/q/38499261/1190388 – hjpotter92

+0

@ hjpotter92鏈接的答案可以用於等待多個條件的實現,您的問題似乎只有一個停止條件,在這種情況下,[KISS](https://en.wikipedia.org/wiki/KISS_principle)是一個好原則:) –