簡體   English   中英

使用 shell_exec 通過 PID 獲取 python 腳本文件名

[英]Get python script filename by PID using shell_exec

問題

我正在使用 PHP 與眾多 Python 服務進行交互。

這是 PHP 使用 bash 啟動進程並獲取 PID 的方式:

$created_pid= shell_exec("nohup python3.8 -u $python_filename >> $log_filename & echo $!");
echo json_encode([
    "resolved"=>true,
    "pid"=>trim($created_pid)
]);

這完美地記錄了啟動的 PID。 但是,我還想編寫一個 function 來檢查 PID 是否仍然處於活動狀態,以及它是否與$python_filename中包含的正確腳本相關聯。

我試過的

所以讓我們假設$python_filename = "test.py"$created_pid = 29780

我嘗試使用此命令根據 PID 檢索進程信息:

$ ps -p 29780

哪個輸出:

29780 pts/0    00:00:00 python3.8

是的,它告訴我這是一個python3.8進程,我很高興但不滿意。 我特別需要知道它是否是test.py腳本。


另一方面,如果我執行:

$ ps -ef | grep "python"

輸出一些難以解析的東西:

root     29780 29615  0 17:26 pts/0    00:00:00 python3.8 -u test.py

所以基本上接近我期望的解決方案 我正在尋找的只是最后一個 bash 命令的清潔 output ,它只包含test.py

“快速而骯臟”的解決方案是只提取命令字符串中的最后一個“字段”,因為我們知道文件名在 position 中:

$ python test.py &
[1] 8040
$ ps -p 8040 --no-headers -o cmd | awk '{ print $NF }'
test.py
$

we tell ps to print just the command string of the process without the columns header ( ps -p 8040 --no-headers -o cmd ) and we tell awk to extract just the last space separate field of the input line ( awk '{ print $NF }' )。 $NFawk中的自動變量,它保存當前記錄中的“字段數”。

如果您的文件名包含空格,這將失敗,因為awk默認將空格解釋為字段分隔符:

$ mv test.py test\ with\ spaces.py
$ python test\ with\ spaces.py &
[1] 9033
$ ps -p 9033 --no-headers -o cmd | awk '{ print $NF }'
spaces.py
$

正如我所說,這是一個快速而骯臟的解決方案,與我在評論中的第一次嘗試相比略有改進。

編輯

經過一番思考,我可能找到了一個更好的解決方案,它更針對“仍在運行的檢查”而不是“從命令中提取腳本文件名”。

由於您知道並存儲了 PID -> 文件名關聯,因此您可以 grep 獲取命令字符串中的文件名,只需檢查 grep 的退出代碼: 0匹配,運行; 1不匹配,不運行。

ps -p 11873 -o cmd | grep -q 'test with spaces.py'

例如

$ python test\ with\ spaces.py &
[4] 11873
$ ps -p 11873 -o cmd | grep -q 'test with spaces.py' && echo running || echo not running
running
$ ps -p 999 -o cmd | grep -q 'test with spaces.py' && echo running || echo not running
not running
$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM