2

I want to run a python script in a button press event of a php/html file. I tried following. Is this possible with PHP exec()? But following didn't work. What is wrong with my code?

HTML file

<html>
<head></head>
<body>
<H3>Run Python Script...</H3>
<form name="input" action="test2.php" method="get">
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP exec()

<html>
<head></head>
<body>
<H3>Executing...</H3>
<?php exec("first.py"); ?>
<H3>Completed...</H3>
</body>
</html>

3 Answers 3

2

exec Executes a command as if on the command line, running first.py just via bash won't work. You have two options:

Option A

You can tell the python parser explicitly to run the file with:

exec('python first.py');

Option B

Make sure your python script's first line is the path to python:

#!/usr/bin/python

#Python code...

Then call exec('./first.py')

(If you chose this option, you'll need to make sure the script is executable)

Conclusion

I'd probably go with option A as it's simplest and gets the job done without fuss.

Hope this helps :) x

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

1 Comment

Thanks Emily, got some insight :)
1

There can be several problems with even your python script.

First: Can you run this script from console? (Do you have a #!/path/to/env/python in the script's beginning)? If not, then either add it to your script or to the exec function (without #!)

You can also use passthru instead of exec, so you can display the raw output of the script.

1 Comment

Hey thanks, this 'passthru' worked for a simple script with one print line, but my script didn't work?
1

try exec("/usr/bin/python path/to/first.py")

1 Comment

My answer answers his question "What is wrong with my code?" enough, it has been tested before, so if you're desperate for points and cannot add anything beneficial here , don't try to make others' answers look bad, go get a life.

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.