奇怪的python错误子流程检查_

2024-04-19 16:35:03 发布

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

我在pythonsubprocess.check_call()函数中遇到了一个非常奇怪的错误。“这两个测试都会失败,因为这两个测试都会失败。”

# Test #1
import subprocess
subprocess.check_call(['git', 'clone', 'https://github.com/achedeuzot/project',
                       '/var/vhosts/project'], shell=True)

# Shell output
usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           [-c name=value] [--help]
           <command> [<args>]

The most commonly used git commands are:
[...]

现在进行第二个测试(“预期行为”测试):

^{pr2}$

第二个错误是正确的。我确实没有权限。但为什么这两个电话有区别呢?我认为使用单个字符串或列表与check_call()函数是一样的。我已经阅读了python documentation和各种用法示例,它们看起来都是正确的。在

有人也有同样奇怪的错误吗?或者有人知道为什么当命令应该完全相同时,输出会有差别吗?在

旁注:Python3.4


Tags: path函数nonamehttpstestimportgit
2条回答

从第一个中删除shell=True。如果您仔细阅读子流程模块文档,您将看到。如果shell=False(默认),第一个参数是包含参数和all的命令行列表(或者是只包含命令的字符串,根本不提供任何参数)。如果shell=True,那么第一个参数是一个表示shell命令行的字符串,然后执行一个shell,它依次为您解析命令行并用空格分隔(这可能是您不希望它做的更危险的事情)。如果shell=True并且第一个参数是一个列表,那么第一个列表项是shell命令行,其余的作为参数传递给shell,而不是命令。在

除非你知道你真的,真的需要,总是让shell=False。在

以下是文档中的相关信息:

If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

相关问题 更多 >