子进程使用双向,但结果不是sam

2024-05-06 06:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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

第二条路是对的,但第一条路为什么不对


Tags: infromimporttrueoutputcheckas方式
1条回答
网友
1楼 · 发布于 2024-05-06 06:41:57

引用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脚本输出是不同的

相关问题 更多 >