PHP获取python进程并将其终止。 XAMP /视窗

时间:2016-07-04 04:50:10

标签: php python windows xampp

如何获取所有python进程以及每个进程的参数并通过PHP Xampp / Windows将其终止

3 个答案:

答案 0 :(得分:4)

在Windows上有三个系统命令来获取进程:

tasklist,可能是最简单的(虽然你无法访问args)。

get-process,需要powershell,无法看到它的输出我没有PowerShell

应该满足您的需求:wmic process

因此,您应该在PHP中使用system()运行此命令,以便获取输出,然后解析它,当您获得进程ID时,使用另一个系统命令来终止它:

taskkill /PID 99999 #replace 99999 with the process id.

答案 1 :(得分:3)

您可以通过tasklist功能使用taskkillshell_exec命令。以下Task演示了如何使用它们来查找有关任务的信息以及如何杀死它们。

class Task {
    function __construct($header,$row) {        
        $this->imageName   = $this->findValue($header,$row,'Image Name');
        $this->processID   = $this->findValue($header,$row,'PID');
        $this->commandLine = $this->findValue($header,$row,'Window Title');
    }

    function findValue($header,$row, $key , $default = '') {
        $kk = array_search($key, $header);
        return $key !== -1 ? $row[$kk] : $default;
    }

    public $imageName   = '';
    public $processID   = '';
    public $commandLine = '';

    public function kill(){
        shell_exec( sprintf('taskkill /PID %s',$this->processID));
    }


    public static function findTask($imageName) {
      $csv  = shell_exec(sprintf( 'tasklist /FO CSV /V /FI "IMAGENAME eq %1$s"',$imageName));
      $lines = explode("\n",$csv);
      array_pop($lines);
      if ( count($lines) <= 1 ) {
          return array();
      }      
      $data = array_map('str_getcsv', $lines);

      $tasks = array();
      $header = $data[0];
      for( $kk = 1 ; $kk < count($data); $kk++ ) {
          $row = $data[$kk];
          if ( count($row) === count($header) ) {
              array_push($tasks, new Task($header, $row));
          }     
      }
      return $tasks;
    }
}

foreach( Task::findTask('python.exe') as $task ) {    
    echo sprintf("%s %s %s\n", $task->imageName , $task->processID, $task->commandLine);
    $task->kill();
}

答案 2 :(得分:0)

<?php
$list = str_replace(' ','|',shell_exec('tasklist'));
$split = explode("\n", $list);
$extension = 'py';
foreach ($split as $item) {
  preg_match_all('#((.*)\.'.$extension.')[\|]+([0-9]+)#',$item, $matches);
  if($matches[1][0] != '' and $matches[3][0] != ''){
    echo $matches[1][0].' '.shell_exec('Taskkill /pid '.$matches[3][0]).PHP_EOL;
  }
}
相关问题