python中的commands模塊,執行出錯:'{' 不是內部或外部命令,也不是可運行的程序 或批處理文件。


最近發現了python的commands模塊,查看了下源碼,使用的popen封裝的,形成三個函數getstatus(), getoutput(), getstatusoutput()

源碼如下:

def getstatus(file):
    """Return output of "ls -ld <file>" in a string."""
    import warnings
    warnings.warn("commands.getstatus() is deprecated", DeprecationWarning, 2)
    return getoutput('ls -ld' + mkarg(file))


# Get the output from a shell command into a string.
# The exit status is ignored; a trailing newline is stripped.
# Assume the command will work with '{ ... ; } 2>&1' around it..
#
def getoutput(cmd):
    """Return output (stdout or stderr) of executing cmd in a shell."""
    return getstatusoutput(cmd)[1]


# Ditto but preserving the exit status.
# Returns a pair (sts, output)
#
def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    import os
    pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts, text

  通過查看以上源碼,發現主要使用的是函數getstatusoutput()。

我調用這個函數的時候,每次的執行結果都是:'{' 不是內部或外部命令,也不是可運行的程序 或批處理文件。

懷疑是getstatusoutput()中的這句話pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')有問題。但是想想這是官網提供的模塊,按說不會出現這種問題。

把pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r'),修改為pipe = os.popen('{ ' + cmd + '; }2>&1', 'r'),就是把2>&1前的空格去掉,結果執行沒有'{' 不是內部或外部命令,也不是可運行的程序 或批處理文件錯誤了,但是沒有執行結果。

目前不知道怎么解決這個問題,可能是系統的問題吧。

別人使用相同的代碼,執行結果正確。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM