简体   繁体   English

运行 python 脚本并使用 PHP 传递变量

[英]Run python script and passing variables using PHP

Hi am having trouble passing a variable from PHP to python.您好在将变量从 PHP 传递到 python 时遇到问题。 It is not displaying on the webpage它没有显示在网页上

PHP PHP

<?php 
  $item='example';
  exec("python pytest.py $item");
?>

Python Python

import sys
print(sys.argv[1])

I am running WAMP and both the PHP and Python file is in the same working directory.我正在运行 WAMP,PHP 和 Python 文件都在同一个工作目录中。 However, nothing is displayed on the PHP webpage.但是,PHP 网页上没有显示任何内容。 Please help, thank you.请帮忙,谢谢。

I think the only thing you are missing in your PHP script is echo .我认为您在 PHP 脚本中唯一缺少的是echo

If you call exec("python pytest.py $item");如果你调用exec("python pytest.py $item"); PHP won't just print the output of the called command. PHP 不会只打印调用命令的 output。

You need to echo shell_exec("python pytest.py $item");你需要echo shell_exec("python pytest.py $item"); . .

The difference between exec and shell_exec is that shell_exec will return the output of the command but exec won't. execshell_exec的区别在于 shell_exec 将返回命令的 output 而exec不会。 You can read more about it here: https://www.php.net/manual/en/function.shell-exec.php and https://www.php.net/manual/en/function.exec.php . You can read more about it here: https://www.php.net/manual/en/function.shell-exec.php and https://www.php.net/manual/en/function.exec.php .

Also make sure the user, which is running the PHP-File, has permissions on the pytest.py file.还要确保运行 PHP 文件的用户对 pytest.py 文件具有权限。

To call a Python file from within a PHP file, you need to call it using the shell_exec function.要从 PHP 文件中调用 Python 文件,您需要使用 shell_exec function 调用它。

For example例如

<?php
    $command = escapeshellcmd('/usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

This will call the script.这将调用脚本。 But in your script at the top, you'll need to specify the interpreter as well.但是在顶部的脚本中,您还需要指定解释器。 So in your py file, add the following line at the top:因此,在您的 py 文件中,在顶部添加以下行:

#!/usr/bin/env python

Alternatively you can also provide the interpreter when executing the command.或者,您也可以在执行命令时提供解释器。

For example例如

<?php
    $command = escapeshellcmd('python3 /usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

other alternate way to do is其他替代方法是

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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