4

Trying a very simple task. Call python example.py from a php script from a windows xampp server.

Notes:
- Both files are in the same directory.
- Going to http://example.com/example.py works fine.
- Going throught the command line (cd inside where example.py is then (python example.py)) works also.

example.py

#! C:{path-to-python.exe}
print("Content-Type: text/html\n")
print("<html>")
print("<h1>Something.</h1>")

index.php

<?php
   $command = escapeshellcmd('python example.py');
   $output = shell_exec($command);
   echo $output;
?>

Nother note:
- If I use $command = escapeshellcmd('example.py'); it opens the python script in my text editor.

Someone tell me plz what am I doing wrong. Thank you.

5
  • What is your default way of opening files with the '.py' extension? If it's text editor, change it to python! You can find it under menu, default apps. Commented Dec 18, 2019 at 1:37
  • I seem to have changed the default opening of '.py' to notepad++. I've reverted that to the 'python.exe'. I checked if it works with ($command = escapeshellcmd('python example.py');) but it just does nothing, then like this ($command = escapeshellcmd('example.py');) and it works but it prints out including the 1st line. That does no happen if i go directly to the py webpage. Commented Dec 18, 2019 at 2:40
  • Maybe it runs the code in stead of checking the string. try to set the string as variable, then pass the variable into escapeshellcmd Commented Dec 18, 2019 at 2:49
  • You need to specify the full path. To simplify for testings, try to put the python executable in the same folder. Commented Dec 18, 2019 at 5:39
  • I restarted the xampp a few times an It started to work with the python command $command = escapeshellcmd('python example.py');. Now the only thing that is bodering me is that the print("Content-Type: text/html\n") still prints out as a string. Commented Dec 18, 2019 at 13:07

1 Answer 1

1

to call python script from php :

$result=exec("python test.py ");

if you want to passing parameters to python script :

$result=exec("python test.py param1 param2");

in python script if you want get parameters:

import sys
param1=sys.argv[1]
param2=sys.argv[2]

note : $result in php taking first print statement in python script

Sign up to request clarification or add additional context in comments.

1 Comment

note: if you need to send json file as parameter from php to python you must encode json file e.g... base64 because in send parameter remove all (") from json file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.