从php运行python文件不会生成输出fi

2024-04-24 08:59:33 发布

您现在位置:Python中文网/ 问答频道 /正文

从php运行另一个文件时遇到问题。我希望我的php参数是运行一个python文件(它调用另一个文件本身)的输出。在

这是我的php文件:

<?php
    if (isset($_POST['submit'])) {
    $params = solve();
}

function solve() {
  exec("python array.py", $output);
  return $output;
}
?>

如果数组.py只是:

^{pr2}$

我将得到1,2,3,4作为我的输出,但我一改变数组.py调用操作系统,我什么也没得到。所以新的数组.py是:

import os

def main():
    os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4


def output():
    f = open("tmp.txt", "r")
    myReturn = []
    currentline = f.readline()

    while currentline:
          val = currentline[:-1]  #Getting rid of '\n'
          val = int(val)
          myReturn = myReturn + [val]
          currentline = f.readline()
    f.close()
    return myReturn


if __name__ == "__main__":
     main()
     o = output()
     print o[0]
     print o[1]
     print o[2]
     print o[3]

如果我只是跑测试.py,输出为文件tmp.txt文件公司名称:

 1
 2
 3
 4

现在,当我运行php文件时,输出tmp.txt文件甚至没有在目录中创建,因此我也没有从php中获得任何输出。 我不知道为什么会这样,因为当我刚跑步的时候数组.py我自己得到所需的输出,然后创建tmp文件。在

编辑: 我忘了包括:导入操作系统以上。在


Tags: 文件pytxtoutputreturnifmainval
1条回答
网友
1楼 · 发布于 2024-04-24 08:59:33

将exec更改为:

exec("python array.py 2>&1", $output)

或者查看web服务器或php错误日志。这将把python脚本的错误输出返回到php脚本(通常不是您在生产中想要的)。在

相关问题 更多 >