Getting output from Python script in Python tests

情到浓时终转凉″ 提交于 2020-01-07 05:27:06

问题


I've got a simple python script in file 'bin/test':

#!/usr/bin/env python

import argparse

PROGRAM_NAME        = "name"
PROGRAM_VERSION     = "0.0.1"
PROGRAM_DESCRIPTION = "desc"
parser = argparse.ArgumentParser(prog=PROGRAM_NAME, description=PROGRAM_DESCRIPTION)
parser.add_argument('--version', action='version', version='%(prog)s ' + PROGRAM_VERSION)

args = parser.parse_args()

When I run it with the --version param, or --help, it prints everything OK:

$ bin/test --version
name 0.0.1

$ bin/test --help
usage: name [-h] [--version]

desc

optional arguments:
  -h, --help  show this help message and exit
  --version   show program's version number and exit

When I run the file using subprocess.check_output, it doesn't get anything:

>>> subprocess.check_output(["bin/test", "--help"],  stderr=subprocess.STDOUT, shell=True)
''
>>> subprocess.check_output(["bin/test", "--version"],  stderr=subprocess.STDOUT, shell=True)
''

I'm using Ubuntu 11.10 with Python version:

python --version
Python 2.7.1+

I need to get the script output in tests. How should I do that?


回答1:


If you're using shell=True, don't pass the program and its arguments as a list. This works:

subprocess.check_output("bin/test --help",  stderr=subprocess.STDOUT, shell=True)

Edit: of course, leaving shell as False would have worked too.

Edit2: the documentation explains why

On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.



来源:https://stackoverflow.com/questions/9095733/getting-output-from-python-script-in-python-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!