我有一個函數執行shell命令來部署服務器在機器上。這個函數接受下列參數:輪詢最大的wait_time,除非條件在python 2.7
- 目錄路徑
- 命令
- 服務器端口
- 等待時間
現在,一旦command
從directory 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]
似乎是一個簡單的方法......說不上來爲什麼我跳入https://stackoverflow.com/q/38499261/1190388 – hjpotter92
@ hjpotter92鏈接的答案可以用於等待多個條件的實現,您的問題似乎只有一個停止條件,在這種情況下,[KISS](https://en.wikipedia.org/wiki/KISS_principle)是一個好原則:) –