【发布时间】:2016-01-22 19:35:38
【问题描述】:
我有一个 Python 脚本,可以让我检查 PHP 文件语法。
我使用 subprocess.check_output 命令调用 bash 命令,但它只返回显示响应的一半。
check_php.py 文件:
#!/usr/bin/python
# coding:utf-8
import os
import sys
import subprocess
import argparse
import fnmatch
import ntpath
path_base = os.path.dirname(os.path.realpath(__file__))
parser = argparse.ArgumentParser(
description="This command checks the PHP syntaxe of files"
)
parser.add_argument('--path', '-p',
help="Path for .php searching"
)
parser.add_argument('--file', '-f',
help="Path of file to check"
)
args = parser.parse_args()
def check_php_file(path_file):
command = 'php -l '+path_file
sortie = ''
try:
sortie = subprocess.check_output(command, shell=True)
except Exception as e:
sortie = str(e)
return sortie
if args.path:
if args.path.startswith('/') or args.path.startswith('~'):
path_base = args.path
else:
path_base = os.path.join(path_base, args.path)
if args.file:
if args.file.startswith('/') or args.file.startswith('~'):
path_file = args.path
else:
path_file = os.path.join(path_base, args.file)
response = check_php_file(path_file)
print("_____"+response+"_____")
checking.php 文件(有语法错误):
<?php
if (true {
echo "True";
}
检查PHP文件的命令:
python check_php.py -f checking.php
命令后显示的输出:
PHP Parse error: syntax error, unexpected '{' in /home/jedema/checking.php on line 3
_____Command 'php -l /home/jedema/checking.php' returned non-zero exit status 255_____
所以,我的 Python 代码可以处理以下响应:
Command 'php -l /home/jedema/checking.php' returned non-zero exit status 255
但我还想在字符串中得到以下响应:
PHP Parse error: syntax error, unexpected '{' in /home/jedema/checking.php on line 3
你有什么想法得到完整的回应吗?
编辑我已经阅读了以下问题:Get bash output with python
解决方案(受萨洛回答的启发)
安装Sh:
pip install sh
通过添加这些导入来工作:
import sh
然后,使用这个 check_php_file_method :
def check_php_file(path_file):
sortie = ''
try:
sortie = sh.php('-l', path_file)
except sh.ErrorReturnCode_255 as e:
sortie = format(e.stderr)
return sortie
【问题讨论】:
-
您在 if(true 之后收到 PHP Parse error: syntax error, unexpected '{' in /home/jedema/checking.php on line 3 because your code is missing )
-
@pregmatch,这不是我的问题的主题。我想检测这个语法来报告它。
-
对不起。我没有正确理解你。
-
我编辑了你的问题的标题,希望你不要介意。
-
这是一个非常好的编辑。谢谢安德拉斯·迪克!
标签: python bash shell command-line