Jack
Jack

Reputation: 753

Running a python code with php

I have a python script which is needed to be run by php:

     <?php
     $command = escapeshellcmd('/home/Desktop/test.py');
     $output = shell_exec($command);
     echo $output;

     ?>

The out put of the python script is a binary file but I get the following error in the log: Unable to access the X Display, is $DISPLAY set properly?

The php code works fine from the terminal but no luck when I try to run it from the browser. Any idea what is going on? Ideally, I don't want to change my program. I want to know how you can rectify the X Display error. Is there a way to check if $DISPLAY is set properly? ( I am working with Ubuntu)

I tried this : pidof X && echo "yup X server is running" on my terminal and it is saying yup x server is running!

Upvotes: 3

Views: 619

Answers (3)

Anupam
Anupam

Reputation: 717

try popen

$command = "/usr/bin/python /home/Desktop/test.py";
$handle = popen($command, "r");

"r" for read

$read = fread($handle, 10);

10 is the size of output you want to take,

echo $read ;

hope it helps,

Upvotes: 0

user149341
user149341

Reputation:

Add the following text as the first line of your Python script:

#!/usr/bin/python

Without this, the kernel doesn't know what interpreter to run your script with, and may end up trying to launch it using /usr/bin/import (because that word probably appears on the first line of the script). The import utility requires access to the X11 display (it's a screenshot utility, basically), which is why you're getting this error.

Upvotes: 1

TechnicalChaos
TechnicalChaos

Reputation: 452

The python file you need may need to open a window to run. You say you saw it run in terminal though? What's test.py? Is it propitiatory? If you try using this as a command in your PHP: (not 100% that the shell escape won't strip this so may need to comment that out)

python -c \'print \"Test\"\' 

and see if you get the output text back. If so it's a python issue not PHP and the test.py file may be instantiating something that needs the $DISPLAY var set. PHP doesn't set the $DISPLAY var as it is shell commands not GUI.

Upvotes: 0

Related Questions