簡體   English   中英

在返回輸出之前在后台運行的Python子進程

[英]Python subprocess running in background before returning output

我有一些Python代碼,我想用perf調試。 為此我想使用子進程。 以下命令返回進程的指令相關信息,直到通過Ctrl ^ C退出命令。

perf stat -p <my_pid>

現在,我想在后台運行Python代碼,直到我希望能夠終止其操作並打印命令輸出。 顯示我的意思:

x = subprocess.call(["perf","stat","-p",str(GetMyProcessID())])

.. CODE TO DEBUG ..

print x   # I want to terminate subprocess here and output 'x'

現在,我想確定在'print x'行做什么來終止進程並檢查輸出。 任何想法/幫助表示贊賞。

提前干杯謝謝,

使用subprocess.Popen運行perf 然后,使用pipe.communicate()發送輸入並獲取進程的輸出。

完成后,調用pipe.terminate()來終止進程。

例如:

pipe = subprocess.Popen(["perf","stat","-p",str(GetMyProcessID())], stdout=PIPE)

pipe.terminate()
stdout, stderr = pipe.communicate()
print stdout

第一:我建議不要在你的python進程中調用perf (正如你在下面的任務的復雜性中看到的那樣),而是使用來自命令行:

sudo perf stat -- python test.py

如果你真的想在python中調用perf,那么你將面臨一些棘手的問題:

  1. 終止perf並使其輸出,你需要給它發送收集到的性能統計SIGINT信號(嘗試一下與sudo perf stat -p mypidctrl-\\將打印什么,而ctrl-c會)
  2. 你需要捕獲stderr因為perf將其輸出發送到stderr (至少在我的版本中)
  3. 你需要使用fork() ,一個進程發送SIGINT ,另一個進程在進程SIGINT讀取它的輸出。 沒有分支它將無法工作,因為在SIGINT ed perf過程之后,您無法再從stdin讀取過程已經消失,並且當您從stdin讀取時,您將無法獲得任何輸出,直到perf正確終止。

這意味着你最終會得到這個python程序:

import subprocess
import os
import signal
import time

perf = subprocess.Popen(['perf', 'stat',  '-p', str(os.getpid())], stderr=subprocess.PIPE)

# <-- your code goes here

if os.fork() == 0:
    # child
    time.sleep(1)  # wait until parent runs `stderr.read()`
    perf.send_signal(signal.SIGINT)
    exit(0)

# parent
print("got perf stats>>{}<<".format(perf.stderr.read().decode("utf-8")))

time.sleep(1)位是丑陋的,它會做什么,但我想它會對99%的情況起作用。 它對perf數據幾乎沒有影響,它對“總運行時間”( *xx seconds time elapsed )的唯一影響

暫無
暫無

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

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