简体   繁体   中英

Running Python scripts from using PHP exec()

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>

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM