简体   繁体   English

调用python版本检查的子进程在标准输出中返回空

[英]subprocess invoking python version check returns empty in stdout

I have this code in Python我在 Python 中有这段代码

import subprocess
pp = subprocess.Popen(
   ['/bin/python', '-c', "'import sys; print(sys.version_info.major)'"],
   stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(pp.communicate())

print(
    subprocess.check_output(
      ['/bin/python', '-c', "'import sys; print(sys.version_info.major)'"])
)

Both versions end up with an empty string (or bytes).两个版本都以空字符串(或字节)结束。 Tested in Py3 and Py2 as well.也在 Py3 和 Py2 中进行了测试。 Why is that the case?为什么会这样?

The problem is the second set of quotation marks.问题是第二组引号。 The command list ['python', '-c', "'import sys; print(sys.version_info.major)'"] translates to this shell command命令列表['python', '-c', "'import sys; print(sys.version_info.major)'"]转换为这个 shell 命令

python -c "'import sys; print(sys.version_info.major)'"

which is not what you intended as it just asks Python to "execute that string", and that doesn't result in any output to stdout .这不是您想要的,因为它只是要求 Python“执行该字符串”,并且不会导致任何输出到stdout

So remove the extraneous quotation marks: ['python', '-c', 'import sys; print(sys.version_info.major)']所以删除多余的引号: ['python', '-c', 'import sys; print(sys.version_info.major)'] ['python', '-c', 'import sys; print(sys.version_info.major)'] . ['python', '-c', 'import sys; print(sys.version_info.major)'] The subprocess module takes care of proper escaping. subprocess模块负责正确的转义。 From the docs :文档

Note in particular that options (such as -input ) and arguments (such as eggs.txt ) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces) are single list elements.请特别注意,在 shell 中由空格分隔的选项(例如-input )和参数(例如eggs.txt )位于单独的列表元素中,而在 shell 中使用时需要引用或反斜杠转义的参数(例如包含空格的文件名)是单个列表元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM