【问题标题】:Get all output of bash command in Python在 Python 中获取 bash 命令的所有输出
【发布时间】: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


【解决方案1】:

使用subprocess.Popen,它返回输出和错误的元组

child = subprocess.Popen(['php','-l', path_file], stdout=subprocess.PIPE, shell=True)
output, error = child.communicate()

【讨论】:

  • 引用stackoverflow.com/a/8984492/5388440:改用 script_response = subprocess.check_output(["php", "/path/to/your/script.php"])。
  • 谢谢。我试过了,但我无法显示输出和错误。我添加了我尝试过的新 check_php_file 函数,而 print(sortie) 什么也不显示,这与 print(error) 的行为相同。
【解决方案2】:

我会使用sh 来满足这些需求。 一个例子:

如果我有一个返回非零返回码的脚本并在 stderr 上打印这样的内容(命名为 test_external_command.sh):

#!/bin/bash
>&2 echo "my Error on STDERR!"
exit 255

我想在一个变量中包含标准错误,我可以在 Python 脚本中使用sh 模块,如下所示(命名为checker.py):

import sh

def main():
    my_cmd = sh.Command('/path/to/test_external_command.sh')
    try:
        my_cmd()
    except sh.ErrorReturnCode_255 as e:
        print 'expected return code'
        print 'STDERR was: {}'.format(e.stderr)


if __name__ == '__main__':
    main()

可以看到stderr作为stderr属性保存在sh.ErrorReturnCode_255中。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2015-06-19
    • 2013-01-01
    • 2012-09-26
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多