commands標(biāo)準(zhǔn)錯誤輸出

問題
在使用commands模塊時,屏幕輸出標(biāo)準(zhǔn)錯誤無法輸出到文件中,無法定位問題

#!/usr/bin/env python
# date: 2020-03-12

import commands

def test_cmd(cmd):
    status, output = commands.getstatusoutput("ls -l '{}' 2>&1".format(cmd))
    print(status)
    print('-'*100)
    with open('w.log', 'a+') as f:
        f.write(output)

if __name__ == '__main__':
    test_cmd('/opt')
    test_cmd("/DON'T TUCH/")

分析
在使用Python之commands模塊時,雖然getstatusoutput方法返回一個元組,但是如果shell命令如果錯誤,及時將output寫入文件,也是無法捕獲標(biāo)準(zhǔn)錯誤輸出

解決
可以在執(zhí)行腳本時,再增加標(biāo)準(zhǔn)錯誤到重定向

[root@localhost py_script]# python p1_command.py >> q.log 2>&1
[root@localhost py_script]# cat w.log 
總用量 0
drwxr-xr-x. 4 root root 104 12月 20 04:44 day_1217
drwxr-xr-x. 2 root root   6 12月 18 05:31 git-learn
drwxr-xr-x. 2 root root  30 12月 26 07:04 mysql_test
drwxr-xr-x. 2 root root  50 3月  13 04:00 py_script
[root@localhost py_script]# cat q.log 
sh: -c:行0: 尋找匹配的 `'' 是遇到了未預(yù)期的文件結(jié)束符
sh: -c:行1: 語法錯誤: 未預(yù)期的文件結(jié)尾
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容