search
HomeBackend DevelopmentPHP ProblemHow to run Python script in PHP program

(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(&#39;python ceshi.py&#39;, $out);
// $re = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $re);
var_dump($out);
echo &#39;<br/>&#39;;
var_dump($re);

ceshi.py

def send():
    data = &#39;1,2,3,4,5&#39;
    print(data)
if __name__ == &#39;__main__&#39;:
    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 = &#39;这是PHP传过来的参数&#39;;
$canshu2 = date(&#39;Y-m-d&#39;);
$re = exec("python ceshi.py $canshu1 $canshu2");
$re = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $re);
var_dump($re);

test.py

import sys
def send():
    # a1 = sys.argv[1]
    # a2 = sys.argv[2]
    re = sys.argv[1:]
    data = &#39;1,2,3,4,5,&#39; + &#39;,&#39;.join(re) # 转字符串
    print(data)
if __name__ == &#39;__main__&#39;:
    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 = {&#39;id&#39;:111, &#39;title&#39;:&#39;测试title&#39;}
    dict[&#39;data&#39;] = sys.argv[1:]
    jsonArr = json.dumps(dict, ensure_ascii=False)
    print(jsonArr)
if __name__ == &#39;__main__&#39;:
    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 &#39;这是运行直接输出:&#39;;
$re = system(&#39;python ceshi.py&#39;);
// $re = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $re);
echo &#39;<br/>&#39;;
echo &#39;这是赋值输出:&#39;;
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 &#39;这是运行直接输出:&#39;;
$re = passthru(&#39;python ceshi.py&#39;);
// $re = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $re);
echo &#39;<br/>&#39;;
echo &#39;这是赋值输出:&#39;;
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!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

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

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

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.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

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.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

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

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

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

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

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.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

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

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment