在Windows下从PHP执行Python脚本


executing python script from php under windows

好的,这适用于我的 linux 服务器,但我正在家里的 PC 上测试我的网站,并试图让 php 执行我的 python 脚本,当然 '' 是 WINDOWS,只有 IM 在我的 Linux 机器上时路径会改变。

$pyscript = 'C:''wamp''www''testing''scripts''imageHandle.py';
$python = 'C:''Python27''python.exe';
$filePath = 'C:''wamp''www''testing''uploads''thumbs''10-05-2012-523.jpeg'

exec('$python $pyscript $filePath', $output, $return );

这适用于我的Linux机器,但不适用于我的Windows测试服务器。如何让它在窗口上运行?哦,这也适用于直接从窗口中的命令提示符运行时

编辑:

这是解决方案:

exec("$python $pyscript $filePath", $output);
我之前使用单引号而不是双引号

,将单引号更改为双引号解决了这个问题。

我觉得很奇怪,C:''wamp''....的filePath可以在Linux机器上运行。无论如何,您是否尝试过不逃避斜杠?

该问题可能与几件事有关,包括实现不同程序执行功能的操作系统特定方法。 我建议只浏览不同的选项,我总是将命令放入单个变量中,然后打印出变量,以便我可以看到我将要运行的内容,如果您看到两个斜杠,那么您可能知道没有必要尝试转义斜杠,但是如果不将其打印到屏幕上,您将不知道。

尝试浏览其他流程执行函数,看看什么适合您。http://www.php.net/manual/en/ref.exec.php

我发现最像在命令行运行它的那个是反引号运算符,然后接下来是system

尝试这样的事情。

$pyscript = 'C:''wamp''www''testing''scripts''imageHandle.py';
$python = 'C:''Python27''python.exe';
$filePath = 'C:''wamp''www''testing''uploads''thumbs''10-05-2012-523.jpeg'
$cmd = "$python $pyscript $filePath";
echo $cmd;
`$cmd`

$pyscript = 'C:'wamp'www'testing'scripts'imageHandle.py';
$python = 'C:'Python27'python.exe';
$filePath = 'C:'wamp'www'testing'uploads'thumbs'10-05-2012-523.jpeg'
$cmd = "$python $pyscript $filePath";
echo $cmd;
`$cmd` 

编辑:啊! 我刚刚想通了,你用单个刻度''包围你的命令,这意味着里面的变量没有被替换。 请改用双引号。 这将解决问题,但我仍然建议在运行命令之前回显命令,以便您看到正在运行的命令,并且能够识别这样的问题。

这是一个非常古老的线程,但仍然出现在Google的第一个结果中,因此值得更新。

2020年,在Python 3.8Windows 10下,正确的解决方案很简单:

<?
$output = shell_exec('C:'path'to'pythonscript.py');
print ($output);
?>

其他所有内容都会导致错误。花了我几个小时才弄清楚。

在XAMPP服务器中,我的 index.py 文件是这样的

from wordsegment import load, segment
load()
print(segment('morerecentlythedevelopmentwhichisapotent'))

我的索引.php文件是这样的

<html>
<head>
  <title>py script</title>
</head>
<body>
  <h1>Hey There!Python Working Successfully In A PHP Page.</h1>
  <?php
    $python = `python index.py`;
    echo $python;
    ?>
</body>
</html>

现在运行索引.php文件。

    Hope this will help you