使用子进程执行的子 Python 没有输出

No output from child Python executed with subprocess

这是一个从命令行运行的简单命令:

> python -c "print('asdasd')"
asdasd

但是从脚本执行时它没有输出任何东西:

import os
import sys
import subprocess

cmd = [sys.executable] + ['-c', '"print(\'asdasd\')"']
print cmd
kwargs = {
  'stdout': subprocess.PIPE,
  'stderr': subprocess.PIPE,
  'stdin': subprocess.PIPE,
}

print subprocess.Popen(cmd).communicate()
print subprocess.Popen(cmd, **kwargs).communicate()

输出:

['C:\Python27\python.exe', '-c', '"print(\'asdasd\')"']
(None, None)
('', '')

为什么它不产生任何东西?我没主意了。在我看来 Python 2.7.11 中的错误。

首先,您不需要在命令行参数中为 '"print(\'asdasd\')"' 添加那些额外的双引号。实际上,您的代码将只执行执行以下操作的 python 代码:"print(\'asdasd\')"。换句话说,它将生成字符串:print(\'asdasd\')

显然,创建字符串不会打印任何内容。这是您的代码的修补版本:

import os
import sys
import subprocess

cmd = [sys.executable] + ['-c', 'print(\'asdasd\')']
print cmd
kwargs = {
    'stdout': subprocess.PIPE,
    'stderr': subprocess.PIPE,
    'stdin': subprocess.PIPE,
}

print subprocess.Popen(cmd).communicate()
print subprocess.Popen(cmd, **kwargs).communicate()

您可能想使用 shlex 模块来解析您的命令行参数。

例如,使用 shlex 模块和字符串格式的三重引号(不要忘记 python 路径的引号,否则将解释反斜杠等字符):

import sys
import shlex
import subprocess

cmd_str = '''"{}" -c "print('asdasd')"'''.format(sys.executable)
print(cmd_str)
cmd = shlex.split(cmd_str)
print(cmd)
kwargs = {
    'stdout': subprocess.PIPE,
    'stderr': subprocess.PIPE,
    'stdin': subprocess.PIPE,
}
print(subprocess.Popen(cmd).communicate())
print(subprocess.Popen(cmd, **kwargs).communicate())

试试这个:

subprocess.Popen(['{} -c "print(\'ECHO\')"'.format(sys.executable)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()