Data interaction between PHP and Python

藏色散人
Release: 2023-04-07 18:02:01
forward
4476 people have browsed it

Recently, I decided to use tp5 for APP interface development and Python for data analysis in a project. Then I faced a question: How do PHP and Python interact with data?

Ideas

The way I solved this problem was to use PHP's passthru function to call the command to run the Python script.

Implementation

Call the command in PHP to run the Python script

//php.php
<?php
$params = "value"; #传递给python脚本的入口参数  
$path="python python.py "; //需要注意的是:末尾要加一个空格
passthru($path.$params);//等同于命令`python python.py 参数`,并接收打印出来的信息 
?>
Copy after login

If there are multiple parameters, separate them with spaces

Receive the parameters passed in by PHP in Python

sys.argv[] is used to obtain the entry parameters passed by PHP into python

//python.py
import sys  
params = sys.argv[1] #即为获取到的PHP传入python的入口参数
print(params);
Copy after login

If in Receive multiple parameters in Python

params = sys.argv[1:]
Copy after login

Return parameters from Python

To return multiple values ​​from Python, you need to write the values ​​into a tuple, and then Convert it to json through json.dumps() and print it. You can get the json printed by the Python script through passthru in PHP

import sys
import json
params = (&#39;Google&#39;, &#39;Runoob&#39;, 1997, 2000);
json_str =json.dumps(params);
print(json_str);
Copy after login

You also need to add @ before passthru in PHP, otherwise the following prompt will be reported

Notice: Array to string conversion in php.php on line 6
Copy after login

Effect

Run the PHP file that calls the Python script, and the output value in the browser is the value printed by Python.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Data interaction between PHP and Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template