(Recommended tutorial: PHP video tutorial)
Introduce how to run Python scripts in php programs,
The running of python programs in php mainly relies on program execution functions.
Here are three related functions: exec(), system() and passthru().
Here we mainly talk about the exec() function, introducing the use of this function to pass parameters,
and how to use python to return josn data for PHP to use.
1. exec()
Execute an external program
exec ( string $command [, array &$output [, int &$return_var ]] ) : string
Parameter description:
command: the command to be executed, It includes three substrings. The first substring is the interpreter of the current system used, the second substring is the location of the script to be executed, and the third substring is an unlimited number of parameters that need to be passed in, with spaces in between. Separate and pay attention to the format. Use spaces to separate substrings.
output: If the output parameter is provided, this array will be filled with the output of the command execution, one element in the array for each line of output. (Note: What is stored in output is not the value of return in python, and all return values will not be saved. What is stored in output is the value output in the python script, which is all the data output by the print() function)
return_var: If both output and return_var parameters are provided, the return status after command execution will be written to this variable.
1. Directly run
index.php
<?php $re = exec('python ceshi.py', $out); // $re = iconv('gbk', 'utf-8', $re); var_dump($out); echo '<br/>'; var_dump($re);
ceshi.py
def send(): data = '1,2,3,4,5' print(data) if __name__ == '__main__': send()
(Important note: If the data returned by the Python script contains Chinese, Need to use iconv('gbk', 'utf-8', $re); for escaping)
2. Pass parameters and receive return data
inde.php
$canshu1 = '这是PHP传过来的参数'; $canshu2 = date('Y-m-d'); $re = exec("python ceshi.py $canshu1 $canshu2"); $re = iconv('gbk', 'utf-8', $re); var_dump($re);
test.py
import sys def send(): # a1 = sys.argv[1] # a2 = sys.argv[2] re = sys.argv[1:] data = '1,2,3,4,5,' + ','.join(re) # 转字符串 print(data) if __name__ == '__main__': send()
Import the sys package and use the sys.argv[] array to get the incoming parameters. The first incoming parameter is sys.argv[1] , the second one is sys.argv[2] and so on. Do not use argv[0]
to receive the returned json data:
import sys import json def send(): dict = {'id':111, 'title':'测试title'} dict['data'] = sys.argv[1:] jsonArr = json.dumps(dict, ensure_ascii=False) print(jsonArr) if __name__ == '__main__': send()
(involving When using Chinese characters, you need to specify ensure_ascii=False)
2. system()
Execute the external program and display the output
system ( string $command [, int &$return_var ] ) : string
Same as the C version of the system() function, this function executes the command specified by the command parameter and outputs the execution result.
If PHP is running in the server module, the system() function will also try to automatically refresh the web server's output cache after each line of output.
If you want to get the raw output of a command without any processing, please use the passthru() function.
index.php
<?php echo '这是运行直接输出:'; $re = system('python ceshi.py'); // $re = iconv('gbk', 'utf-8', $re); echo '<br/>'; echo '这是赋值输出:'; var_dump($re);
The original version of test.py is used here, and the output effect is as follows:
3. passthru()
Execute external programs and display output
passthru ( string $command [, int &$return_var ] ) : void
Similar to the exec() function, the passthru() function is also used to execute external commands (commands). When the executed Unix command outputs binary data and needs to be transmitted directly to the browser, this function needs to be used instead of the exec() or system() function. Commonly used to execute commands such as pbmplus that can directly output image streams. By setting Content-type to image/gif, and then calling the pbmplus program to output a gif file, you can directly output the image to the browser from the PHP script.
index.php
echo '这是运行直接输出:'; $re = passthru('python ceshi.py'); // $re = iconv('gbk', 'utf-8', $re); echo '<br/>'; echo '这是赋值输出:'; var_dump($re);
The original version of test.py is used here, and the output effect is as follows:
(Recommended tutorial: PHP video tutorial)
The above is the detailed content of How to run Python script in PHP program. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment