php调用python脚本
主要参考两篇文章
PHP中的换行详解
利用PHP调试Python
Python小窥 - 写给Python的入门者
这两篇文章结合起来进行测试,主要过程如下
cd /var/www/html mkdir script nano script/test.py #粘贴代码 nano test002.php #粘贴代码
期间主要遇到的问题有
php文件里面的路径/script/test.py,改为script/test.py,作者显然在根目录添加的目录
php换行的实现,想实现,本来用\n,结果失败,于是用<br>,搞定,实现结果如下图
继续修改,发现对于连续迭代语句无法正常打印数据,具体还没查询原因,猜测是由于python本身报错,可以本地运行脚本测试。
另外的测试是中文支持情况,发现中文的时候网页全部空白,显然就是报错了,本来以为是php对中文支持的不好,于是修改了,添加了中文支持,发现情况依旧,于是本地测试python的中文支持情况,发现不支持,按照报错信息
Non-ASCII character '\xe8' in file test.py on line 9, but no encodi
查询解决方法。原来需要开头添加utf8的支持,添加行注释搞定,最终的php脚本内容为
<?php #header("Content-type: text/html; charset=utf-8"); $output = shell_exec('python script/test.py'); $array = explode(',', $output); foreach ($array as $value) { #echo "\n"; echo $value; echo "<br>"; } ?>
python内容为
# coding=utf-8 print 'this is a Python program with PHP,' #print '\n' print "22," print "21," print "26," print "22," print "21," print 'Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five $ print '要求:打印1到100,遇到3的倍数,只打印“Fizz”,遇到5的倍数,打印“Buzz”,同时遇到3,5的倍数,打印“FizzBuzz”,' for x in range(1,101):print"Fizz"[x%3*4:]+"Buzz"[x%5*4:]or x print "," for x in range(1,11):print"qiangge_is_god"[x%3*14:]+"i_can't_believe_it"[x%5*18:]or x print "," False = True if False: print "Hello" else: print "World" print ','
最后显示的效果图