从php运行python脚本并写入文件

时间:2016-03-31 19:00:41

标签: php python

我的php代码在htdocs / series / index.php中。 我的python代码位置是/home/shivam/Desktop/hello.py 我在ubuntu中使用xampp运行php。 这是php代码

 <?php
$command = escapeshellcmd('/home/shivam/Desktop/hello.py');
$output = shell_exec($command);
echo $output;
?>

这是我的python代码

#!/usr/bin/env python
with open("/home/shivam/Desktop/solution.txt", "w") as myfile:
    myfile.write("write text")

我正在尝试使用php运行python脚本来写入'solution.txt'文件。当我自己写一些东西到solution.txt并使用python脚本通过php以读取模式打开它然后它工作,但当我尝试使用上面的代码编写时,我无法这样做。 还有一件事,没有一行下面的代码“with open(”/ home / shivam / Desktop / solution.txt“,”w“)作为myfile:”被执行。 我尝试过在enter link description here

中给出的解决方案

1 个答案:

答案 0 :(得分:0)

可执行文件和文件的绝对路径......

<强> run_py.php

<?php
$command = escapeshellcmd('/usr/bin/python /home/user/some_py.py');
$output = shell_exec($command);
echo $output;
?>

<强> some_py.py

with open("/home/user/solution.txt", "w") as myfile:
    myfile.write("write text")

输出:

user@box:~/$ php run_py.php 
user@box:~/$ cat solution.txt 
write text