1

My php code is in htdocs/series/index.php. My python code location is /home/shivam/Desktop/hello.py I am running php using xampp in ubuntu. here is php code

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

here is my python code

#!/usr/bin/env python
with open("/home/shivam/Desktop/solution.txt", "w") as myfile:
    myfile.write("write text")

I am trying to run the python script using php to write to a file 'solution.txt'. When i write something myself to solution.txt and open it in read mode using python script via php then it works but when i try to write using above code ,i am unable to do so. One more thing, none of the code below the line "with open("/home/shivam/Desktop/solution.txt", "w") as myfile:" gets executed. I have tried the solution given in : enter link description here

Community
  • 1
  • 1
shivam12393
  • 11
  • 1
  • 6

1 Answers1

2

Absolute paths to executables and files...

run_py.php

<?php
$command = escapeshellcmd('/usr/bin/python /home/user/some_py.py');
$output = shell_exec($command);
echo $output;
?>

some_py.py

with open("/home/user/solution.txt", "w") as myfile:
    myfile.write("write text")

Output:

user@box:~/$ php run_py.php 
user@box:~/$ cat solution.txt 
write text
jDo
  • 3,962
  • 1
  • 11
  • 30
  • i know this code is working. But I have to run it on browser. – shivam12393 Apr 01 '16 at 06:18
  • @shivam12393 *"i know this code is working."* Did you actually try running it? Enable PHP error reporting and check if maybe your PHP/server user (www-data?) isn't allowed to write the file. PHP may not be allowed to open a shell. – jDo Apr 01 '16 at 06:27
  • @shivam12393 It would help if you added your debugging input and output to the question. E.g. "I tried adding [code] to the script and got this output: [browser/terminal output]" – jDo Apr 02 '16 at 14:17