gpt4 book ai didi

php - 无法在 PHP 中输​​出 Python Print

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:22 27 4
gpt4 key购买 nike

我真的被这个问题困住了,但我是 Python(和 Raspberry Pi)的新手。我想要的只是从我的 python 脚本输出 print 输出。问题是(我相信)我的 python 脚本中的一个函数需要半秒才能执行,而 PHP 错过了输出。

这是我的 php 脚本:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$cmd = escapeshellcmd('/var/www/html/weathertest.py');
$output = shell_exec($cmd);
echo $output;

//$handle = popen('/var/www/html/weathertest.py', 'r');
//$output = fread($handle, 1024);
//var_dump($output);
//pclose($handle);

//$cmd = "python /var/www/html/weathertest.py";
//$var1 = system($cmd);
//echo $var1;

echo 'end';
?>

我包含了注释 block 以显示我还尝试过的其他内容。三个都输出“static text end”

这是 python 脚本:

#!/usr/bin/env python

import sys
import Adafruit_DHT
import time

print 'static text '

humidity, temperature = Adafruit_DHT.read(11, 4)

time.sleep(3)

print 'Temp: {0:0.1f}C Humidity: {1:0.1f}%'.format(temperature, humidity)

py 在命令行上执行良好。我添加了 3 秒的延迟,使脚本在我自己的测试中感觉更长。

鉴于我总是得到 static text 作为输出,我认为我的问题是 PHP 没有等待 Adafruit 命令。但对我来说最奇怪的是,如果我在命令行上执行 PHP 脚本,即 php/var/www/html/test.php,我的所有三个 PHP 尝试都可以正常工作 - 然后我得到期望的输出:

static text
Temp: 23.0C Humidity 34.0%
end

所以我想有两个问题: 1. 如何让 PHP 等待 Python 完成。 2.为什么PHP命令行与浏览器不同?

最佳答案

  1. How to make PHP wait for Python completion

shell_exec 将等待命令完成

  1. Why does the PHP command line differ from the browser?

我最好的猜测是用户运行命令的不同。在命令行上,脚本以您登录的同一用户身份运行,在“浏览器”上,可能与 apache/nginx 的用户身份相同,两种情况下的环境变量都不同。


在脚本前添加python,即:

$output = shell_exec("python /var/www/html/weathertest.py");
echo $output;

或者使用 python 二进制文件的完整路径:

$output = shell_exec("/full/path/to/python /var/www/html/weathertest.py");
echo $output;

PS:要知道完整路径,请在 shell 上使用 which python

关于php - 无法在 PHP 中输​​出 Python Print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885431/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com