簡體   English   中英

subprocess.check_call出現奇怪的python錯誤

[英]Strange python error with subprocess.check_call

我在python subprocess.check_call()函數中遇到了一個非常奇怪的錯誤。 以下是兩個測試,由於權限問題都應該失敗,但第一個只返回'usage'(“意外行為”):

# 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:
[...]

現在進行第二次測試(“預期行為”):

# Test #2
import subprocess
subprocess.check_call(' '.join(['git', 'clone', 'https://github.com/achedeuzot/project',
                                '/var/vhosts/project']), shell=True)
# Here, we're making it into a string, but the call should be *exactly* the same.

# Shell output
fatal: could not create work tree dir '/var/vhosts/project'.: Permission denied

第二個錯誤是正確的錯誤。 我確實沒有權限。 但為什么這兩個電話之間有區別? 我認為使用單個字符串或列表與check_call()函數相同。 我已經閱讀了python文檔和各種用法示例,看起來都是正確的。

有人有同樣的奇怪錯誤嗎? 或者有人知道為什么在命令完全相同時輸出會有差異嗎?

附注:Python 3.4

從第一個中刪除shell=True 如果仔細閱讀子進程模塊文檔,您將看到。 如果shell=False (默認值),則第一個參數是帶有參數和all的命令行列表(或者只包含命令的字符串,根本不提供任何參數)。 如果shell = True,那么第一個參數是一個表示shell命令行的字符串,執行一個shell,然后為你解析命令行並按空格分割(+更危險的事情,你可能不希望它做)。 如果shell=True且第一個參數是列表,則第一個列表項是shell命令行,其余的作為參數傳遞給shell,而不是命令

除非你真的知道你,真的需要,總是讓shell=False

這是文檔中的相關位:

如果args是一個序列,則第一個項指定命令字符串,並且任何其他項將被視為shell本身的附加參數。 也就是說,Popen相當於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM