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

4
  • Did you also change the permissions as suggested in the link? Commented Mar 31, 2016 at 22:16
  • i did chmod +x hello.py Commented Apr 1, 2016 at 5:57
  • You original code has valid php tags, right? It says ` ?php, not <?php` here. Commented Apr 1, 2016 at 6:02
  • what else permission do i need to give to python and php file. Commented Apr 1, 2016 at 9:45

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

i know this code is working. But I have to run it on browser.
@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.
@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]"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.