子进程

时间:2016-06-20 10:09:54

标签: python 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中的一个错误。

2 个答案:

答案 0 :(得分:1)

首先,在命令行参数中,'"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())

答案 1 :(得分:0)

试试这个:

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