How to execute a function from a Python script (wi

2019-09-08 03:56发布

问题:

I've recently been working on a web crawler with PHP and as a newish PHP coder, I'm not the most advanced. I also know a decent bit of Python and there are a few things I am able to do in Python yet not in PHP.

Is there any way for me to run a Python function with parameters inside a PHP script? Please be specific in your answers as I'm not amazing at PHP.

回答1:

Run the Python script using php's shell_exec function

Think of shell_exec as basically running commands in your terminal. So if you normally run your python script from the shell like this:

/python-scripts/myscript.py "here is an argument"

You would pass the same command into shell_exec, like this:

$output = shell_exec("python-scripts/myscript.py 'here is an argument'");

Note: shell_exec will return the output of the command you run, so save it to a variable if you want to use the output from the python program in your PHP script.

Edits: fixed syntax issues, provided a more specific example