【问题标题】:Could not run python script using PHP无法使用 PHP 运行 python 脚本
【发布时间】:2017-12-06 08:47:21
【问题描述】:

我可以通过在命令行上执行 python 文件来获得输出(在文本文件中),但无法通过使用 php exec() 执行来获得输出(在文本文件中)。我做错了什么?

这是我的python文件(example.py):

inputfile = open("input.txt",r)
data = inputfile.read()
inputfile.close()

outputfile = open("output.txt","w")
outputfile.write(str(data))
outputfile.write(str(data))
outputfile.close()

这是我的 php 文件(example2.php):

<?php 
$string = "hello";
file_put_contents('input.txt', $string);
exec('python example.py');
$result = file_get_contents('output.txt');

我在命令行上输入了这个,它起作用了:

python example.py

【问题讨论】:

标签: php python cmd exec cmdline-args


【解决方案1】:

通过在php中执行一个bat文件来运行python脚本解决了这个问题。

exec('cmd /c ./path/run_example.bat')

这是我写的bat文件:

cd C:\Users\Username\AppData\Local\Programs\Python\Python36 # very important if you are runnning it on a server.
python --version # make sure the version is the same as what you expected
python C:\path\example.py

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2012-06-03
    • 2018-10-23
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多