Problem in executing Python script using PHP

Discussion in 'PHP' started by hassanahmad2, Jun 21, 2012.

  1. #1
    Hello,

    I am using the following function for executing python scripts on my server. The code works fine, unless the python script is importing something such as nltk library for example. I can't figure out why this happens. Can anyone help me out with this? I would really appreciate it.

    Thanks

    
    function execPython($cmd) {
    
    	$output = "";
    
    	$descriptor_spec = array(
    		0 => array("pipe", "r"),
    		1 => array("pipe", "w"),
    		2 => array("file", "./error.log", "a")
    	) ;
    
    	$process = proc_open("python $cmd", $descriptor_spec, $pipes);
    
    	if (is_resource($process)) {
     
    		$output = nl2br(stream_get_contents($pipes[1]));
    
    		fclose($pipes[1]);
    		fclose($pipes[0]);
    
    		$return = proc_close($process);
    		if ($return != 0) $output = "Error";
    	}
    	else $output = "Error";
    
    	return $output;
    }
    
    echo execPython("abc.py");
    Code (markup):
     
    hassanahmad2, Jun 21, 2012 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    have you tried to add the full path to the include?
     
    EricBruggema, Jun 22, 2012 IP
  3. hassanahmad2

    hassanahmad2 Active Member

    Messages:
    243
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    60
    #3
    So, I finally found the solution to the problem. It turned out that I have installed python modules in an alternative directory, so I just had to pass PYTHONPATH environment variable as well to the proc_open function. That did the work :)
     
    hassanahmad2, Jun 23, 2012 IP