问题
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