2015-11-27 20 views
1

我用subprocesscheck_output()函数两种方式,找到结果不一样,我不知道为什么。子过程使用两种方式,但结果不一样

  1. 第一种方式:

    from subprocess import check_output as qc 
    output = qc(['exit', '1'], shell=True) 
    
  2. 方式二:

    from subprocess import check_output as qc 
    output = qc(['exit 1'], shell=True) 
    

错误:

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/home/work/cloud/python2.7_64/lib/python2.7/subprocess.py", line 544, in check_output 
    raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command '['exit 1']' returned non-zero exit status 1 

二方式是对的,但第一种方式为什么不正确?

+0

试试'qc('exit 1',shell = True)'。我想它正在执行'“exit 1”' –

+0

相关:[subprocess.call using string vs using list](http://stackoverflow.com/q/15109665/4279) – jfs

回答

1

报价subprocess docs

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

你真正做到在每种情况下是:

  1. 你传递的参数的顺序:['exit', '1']。序列相当于shell命令exit 1。参数用空格分隔,并且没有引号可以改变分离过程。

  2. 您传递一系列参数:['exit 1'],其长度为1.这等同于shell命令"exit 1"。你的第一个(也是唯一的)参数中有空格,这与把它用引号括起来相似。

正如您可以验证的那样,两个命令的退出代码是不同的,因此您的Python脚本输出是不同的。

相关问题