php exec()函数执行一个外部程序遇到的问题。 20200328exec()执行外部命令失败,但没有任何错误信息。gather.py的代码如下# coding=utf-8 ...
php exec()函数执行一个外部程序遇到的问题。 20200328
exec()执行外部命令失败,但没有任何错误信息。
gather.php和gather.py同目录下
gather.py的代码如下# coding=utf-8 #设置页码编码,解决中文乱码
import re
import requests
#注意这里增加引入了sys库 20200404
import sys
#模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
}
url = 'https://wokan.chawen.org/post/' + sys.argv[1]
#requests获取网页
respose = requests.get(url, headers=headers)
content = respose.text #获取内容
#保存采集的内容到文件
filename = 'test.txt'
f = open(filename, 'w', encoding='utf-8') ##ffilename可以是原来的txt文件,也可以没有然后把写入的自动创建成txt文件
f.write(content)
f.close()
exec执行某命令在命令行下没有问题,但是在php中就出错。这个问题99.99%与权限有关,但是exec执行的命令不会返回错误。一个技巧就是使用管道命令,gather.php(和gather.py同目录下)的exec代码如下:$result=exec("py gather.py",$array,$ret);
var_dump($array);
echo("ret is $ret");
可以改为$result=exec("py gather.py 2&1",$array,$ret);
var_dump($array);
echo("ret is $ret");
使用2&1,命令就会输出shell执行时的错误到$output变量, 输出该变量即可分析。
php脚本输出结果为:array(1) { [0]= string(28) "Can't find a default Python." } ret is 103$result=exec("d:/python/python.exe gather.py 2&1",$array,$ret);
var_dump($array);
echo("ret is $ret");
执行gahter.php文件,ok,成功。文件同目录下生成了test.txt文件,里面保存了采集的结果。
...
仅显示部分内容,浏览全部请登录。
登录 | 立即注册