問題
在使用commands模塊時(shí)伐庭,屏幕輸出標(biāo)準(zhǔn)錯(cuò)誤無法輸出到文件中,無法定位問題
#!/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模塊時(shí),雖然getstatusoutput方法返回一個(gè)元組宅粥,但是如果shell命令如果錯(cuò)誤,及時(shí)將output寫入文件电谣,也是無法捕獲標(biāo)準(zhǔn)錯(cuò)誤輸出
解決
可以在執(zhí)行腳本時(shí)秽梅,再增加標(biāo)準(zhǔn)錯(cuò)誤到重定向
[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: 語法錯(cuò)誤: 未預(yù)期的文件結(jié)尾